I am trying to implement dark mode on my site. So when a button is clicked to go into dark mode, it should apply the "dark" class to the main div and apply the "invisible" class to the paragraph, to hide it in dark mode. When the button is clicked again it should remove the dark class and remove the invisible class. But the opposite is happening, the paragraph is hidden in the light mode and unhidden in the dark mode. Send help.
document.querySelector(".btn").addEventListener("click", function() {
document.querySelector(".main").classList.toggle("dark");
document.querySelector(".main p").classList.toggle("invisible");
})
html,
body {
font-family: 'Fredoka', sans-serif;
height: 100%;
margin: 0;
}
h1 {
font-size: 70px;
margin: 0 0 10px;
}
p {
font-size: 25px;
margin: 30px 0px 20px;
}
.main {
text-align: center;
min-height: 100%;
display: flex;
justify-content: center;
align-items: center;
flex-flow: column;
}
.dark {
background-color: #1a1919;
color: white;
}
.invisible {
display: none;
}
<div class="main">
<div>
<h1 class="heading">Hey there!</h1>
</div>
<div>
<p> Welcome to my cool little website that has a dark mode functionality. <br> If you're an uncultured **** who prefers light mode, then please leave. <br> But if you're not, then click the button below.
</p>
</div>
<div>
<button class="btn">Dark Mode</button>
</div>
</div>
Try this:
document.querySelector(".btn").addEventListener("click",function(){
document.querySelector(".main").classList.toggle("dark");
if(document.querySelector(".main").classList.contains("dark"))
document.querySelector(".main p").classList.remove("invisible");
else
document.querySelector(".main p").classList.add("invisible");
})