Lexington has been awarded a grant from Astro, to celebrate. Get a 30% discount. Apply code LEXINGTON30 at checkout.
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-base-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-black ">
<!-- 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-black 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
Get access to all themes
Unlock all themes for $199 for forever! Includes lifetime updates,
new themes, unlimited projects, and support
— No subscription
needed.