Reputation: 21
I've been trying to have my toggle trigger a dark mode on and off using JavaScript but clearly I'm doing something wrong. I attempted to trigger it by applying the light class to my body and using addClassListener. Below is a simplified version of my code but i also plan on doing this on specific classes as well in order to change font and div colors in each different mode as well. Any suggestions?
HTML
<label class="switch">
<input type="checkbox" checked>
<span id="slide" class="slider round"></span>
</label>
CSS
body{
position: absolute;
top: 320px;
left: 0;
width: 100%;
height: 100%;
background-color: hsl(230, 17%, 14%);
z-index: -1;
}
body.light {
background-color: white;
}
Javascript
const checkbox = document.getElementById('slide');
checkbox.addEventListener('change', ()
==>{document.body.classList.toggle('light');
});
Upvotes: 0
Views: 209
Reputation: 2948
You are attempting to get the element by id
, but you have not defined any id
s in your snippet.
<label class="switch">
<input type="checkbox" checked>
<span id="slider" class="slider round"></span>
</label>
Additionally, you're listening for a change
event on a span
element. The span
element will never fire a change event. If you change that to listen in the input
element, it should fire. Documentation
Upvotes: 1