DEV Community

Cover image for Dark light mode toggle
Rajamanickam
Rajamanickam

Posted on

Dark light mode toggle

In this post, I'm going to show you how you can easily create a Dark/Light mode toggle using CSS, JavaScript.

Create two CSS classes, one for the light mode and one for the dark mode.

Image description

Create a checkbox input in your HTML code to act as the toggle switch:
In this step, we create a checkbox input element that will act as the toggle switch for our dark-light mode. We use the label element to wrap the input element and a span element with the class slider round for the toggle button.

The id attribute of the input element is used to reference the element in our JavaScript code later.

Image description

Add some JavaScript code to toggle the dark mode class
In this step, we use JavaScript to toggle the dark mode class when the toggle switch is clicked. We add an event listener to the input element that listens for the change event and calls the mode function.

Image description

We also use the localStorage object to store the user's preference for light or dark mode, so that the mode persists even when the user leaves and returns to the site. We check the value of localStorage.getItem('mode') to see if the user has previously selected a mode, and if so, we set the data-theme attribute and the toggle button accordingly.

Image description

By following these steps, you can create a dark-light mode toggle that allows your users to switch between different color schemes for your website or web application.

Source will be available on : https://github.com/erajamanickam/dark-light-mode

Live demo : https://dark-light-mode-css.vercel.app/

Watch on video : https://youtu.be/hBzKhTkLGWU

Codepen : https://codepen.io/erajamanickam/pen/JjaBmpB

Top comments (0)