A Dark Mode Switch

The page has a dark version now, but only we can switch it, by editing the code. Visitors need a button. We've added one to the header, the button "Dark mode" with id="theme", and a short script at the end of body:

<script>
	document.querySelector("#theme").addEventListener("click", function () {
		document.documentElement.classList.toggle("dark");
	});
</script>

When someone clicks the button, the script adds the class dark to the <html> element, or removes it if it's already there. That's all it does. You don't need to understand how it's written: you'll learn that in the JavaScript course. Thanks to the line with @custom-variant, all your dark: classes follow this one class.

A real site's switch usually does a little more: it starts with the visitor's system setting, and it remembers their choice for the next visit. That takes a few more lines of JavaScript, but the idea stays the same: the class dark on <html>.

The button itself needs colors for both modes, and a label that says what it does. A label can change with the mode without any script: put both texts into the button, each in its own span, and hide the one that doesn't fit with hidden (display: none):

<span class="dark:hidden">Dark mode</span>
<span class="hidden dark:inline">Light mode</span>

In light mode, the first one shows, and the second one is hidden. In dark mode, it's the other way round: dark:hidden hides the first one, and dark:inline shows the second one (display: inline, so it stays in the line like ordinary text).

Instructions

Remove the class dark from the html element (delete class="dark"), so that the page starts in light mode. Then click the button "Dark mode" in the preview a few times: the page switches between light and dark.

Give the button colors for both modes: add the classes bg-stone-200 hover:bg-stone-300 dark:bg-stone-700 dark:hover:bg-stone-600 to it.

Replace the text of the button with the two span elements from the example above. In light mode, the button now offers "Dark mode", and in dark mode "Light mode".

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

4/5