See the button in the top left corner.
Another from the Florin Pop video
The HTML is simply:
<form id="dark-mode-container">
<input id="toggle" name="toggle" type="checkbox">
<label for="toggle"></label>
</form>
The CSS hides the <input> with visibility: hidden and the <label> is used for the button.
The JS was reasonably straightforward:
const input = document.getElementById('toggle');
input.addEventListener('change', (e) => {
document.body.classList.toggle('dark', e.target.checked);
});
- The
<input>is atype="checkboxtype. The event listener uses achangeevent rather than aclickthough I found both worked the same. - I hadn’t seen the value checked before in
e.target.checked. - A CSS
user-selectproperty is set tononeon the<label>which means it can’t be selected. In the end the text was removed anyway but I haven’t used this property before. It can also take values ofcontain,auto, See MDN for more.