Black Friday: Enjoy a 35% discount on the bundles. Apply the code BLACKFRIDAY35 at checkout! Limited offer.
Let’s recreate the dark mode toggle from the Alpinejs tutorial that we did a while ago.
A dark mode toggle is an important feature for modern web applications due to several reasons:
Tailwind provides a dark mode utility class that can be used to toggle between light and dark mode. This class can be applied to the any element to switch between the two modes.
Understanding the code
dark:bg-neutral-900
: This is a dark mode utility class that sets the background color to gray-900 when the dark mode is enabled.<div class="bg-white dark:bg-neutral-900 ">
<!-- Your content here -->
</div>
dark:text-white
: This is a dark mode utility class that sets the text color to white when the dark mode is enabled.<h1 class="text-neutral-900 dark:text-white ">
<!-- Your text here -->
</h1>
All you have to do si append the dark mode utility class to the element you want to change the color of. If you do not want to have a togggle, you can just add the class to the element directly and it will be applied to all the elements when the user preffrences are set to dark mode on their device, browser, or OS.
document.addEventListener("DOMContentLoaded", function() {
: This is the event listener that will run when the DOM is fully loaded.const toggleButton = document.getElementById("dark-mode-toggle");
: This is the code that will select the element with the ID “dark-mode-toggle”.const body = document.body;
: This is the code that will select the body element.toggleButton.addEventListener("click", function() {
: This is the event listener that will run when the button is clicked.body.classList.toggle("dark");
: This is the code that will toggle the dark mode on and off.document.addEventListener("DOMContentLoaded", function() {
const toggleButton = document.getElementById("dark-mode-toggle");
const body = document.body;
toggleButton.addEventListener("click", function() {
body.classList.toggle("dark");
});
});
This is a simple theme toggle that can be used to switch between light and dark mode. The code is easy to understand and the structure is clear. The use of Tailwind CSS and JavaScript makes it easy to style the toggle and add interactivity.
Hope you enjoyed this tutorial and have a great day!
/Michael Andreuzza
Own all themes forever for $199.
Includes new themes, updates, unlimited projects, and lifetime support. — No subscription required!