Dark Mode Toggle

Page section: playground

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);
});
  1. The <input> is a type="checkbox type. The event listener uses a change event rather than a click though I found both worked the same.
  2. I hadn’t seen the value checked before in e.target.checked.
  3. A CSS user-select property is set to none on 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 of contain, auto, See MDN for more.