Adding a dark mode toggle button on a website is as popular as ever today, so here’s a simple way to do it with JavaScript. Once the HTML and JavaScript is in place, you can adjust the CSS as needed to create the two different themes (dark and light modes).
In your HTML, you’d have a basic checkbox with an associated label:
<input type="checkbox" id="darkToggle">
<label for="darkToggle">
Code language: HTML, XML (xml)
Then in your JavaScript you can trigger the toggle to switch a class on the body element:
let darkToggle = document.querySelector('#darkToggle');
darkToggle.addEventListener('change', ()=> {
document.body.classList.toggle('dark');
});
Code language: JavaScript (javascript)
From there, you simply need to add CSS that uses the “dark” class that gets applied to the body element. You can apply styles directly to the body, but you can also use the descendant selector to target only elements that are children of the class .dark
(e.g. .dark .module
). Below is a simple example that you can expand upon that uses the CSS appearance
property to allow the checkbox to be styled.
Once the basic functionality is in place, you can add the typical sun/moon icons or graphics, you can convert the checkbox to a sliding toggle, and so forth.