I've been creating a night mode for my web page and made a specific class in CSS to apply when it toggles. However it applies to some elements but not for some. But when I write code for each element without classList.toggle it works. I can't figure out what goes wrong. I don't even get errors in console also. I'd really appreciate if you could help me. Thank You.
HTML:
<body id="body">
<div class="top-right">
<button id="nightMode">Night Mode</button>
</div>
<header>
<h2>PHOTOGRAPHER</h2>
<h1>Kylo Ren</h1>
</header>
<section class="pricing" id="price">
<div class="price-section">
<div class="price-card">
<div id="head">
<h3 class="title">Basic</h3>
</div>
<div class="price-sub">
<div class="sub-sec">
<h3>100+ Photos</h3>
</div>
<div class="sub-sec">
<h3>BnW Editing</h3>
</div>
<div class="sub-sec">
<h3>Soft Copy</h3>
</div>
<div class="sub-sec" id="foot">
<h3>$499</h3>
</div>
</div>
</div>
</div>
</section>
<footer id="footer">
<h4>Powered By Kisara Fernando</h4>
</footer>
CSS:
.darkTheme{
background-color: #000;
color: #fff;
}
.lightTheme{
background-color: #fff;
color: #000;
}
JS:
let btn = document.getElementById('nightMode');
let footer = document.getElementById('footer');
btn.addEventListener('click' , changeBg);
function dark(){
btn.classList.toggle("lightTheme");
body.classList.toggle("darkTheme");
footer.classList.toggle("lightTheme");
document.querySelectorAll('#head')[0].classList.toggle("darkTheme");
document.querySelectorAll('#head')[1].classList.toggle("darkTheme");
document.querySelectorAll('#head')[2].classList.toggle("darkTheme");
}
function changeBg(){
dark();
}
None of your element starts with lightTheme
set. Every time you click the button, your button and footer will add/remove the lightTheme (but never the darkTheme), and your body will add/remove the darkTheme.
A solution could be just toggle the darkTheme to both the button and the body (the footer will update with the body):
btn.classList.toggle("darkTheme");
body.classList.toggle("darkTheme");
Note: Your lightTheme class would be completely useless here.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.