This tutorial guides you through creating a dark mode toggle for websites using HTML, CSS, and JavaScript. The guide covers essential concepts like CSS variables, DOM manipulation, and local storage usage.
Let's create a dark mode toggle for your website!
Create an index.html file with the basic HTML structure and import the style.css and script.js files.
Inside the body tag, add necessary elements and a div with the .toggle-container class. Insert the sun and moon SVG icons within it.
This is what our plain index.html file looks like
In your style.css file, use the :root selector to define CSS variables for dark and light colors. This allows for easy theme customization.
Add CSS styles to your base elements (body, container, and heading).
Add the .dark-mode class that swaps the background and text colors when applied to an element.
Add CSS styles for the sun and moon SVG icons, controlling their visibility based on the current mode.
Here's the styled page with a default light theme!
In your script.js file, select the necessary DOM elements: the themeToggle button and the body element.
Create an event listener for the toggle button to switch between light and dark modes by adding or removing the .dark-mode class.
Inside the event listener, use localStorage.setItem() to save the user's theme preference.
On page load, use localStorage.getItem() to check for a saved preference and apply it if it exists.
Now we have a dark mode toggle ready!
You successfully completed the guide!