Hello friends, in this article you will know how to create a dark mode toggle with just vanilla CSS and vanilla JavaScript. This is a written version of the tutorial uploaded on the YouTube channel of ramCoder. Creating this toggle for dark mode is not that hard as we may think. Anyone with some knowledge of CSS variables and JavaScript events can easily understand this code. I have uploaded the source code file in the GitHub repository with the download link at the end of this article. Also, I have embedded the code in the code box in this article also.
I have use CSS variables in order to make this work more easily and seamlessly. This type of dark mode doesn't need to use any of the JavaScript library or CSS library, we can easily make this dark mode toggle with vanilla CSS and vanilla JavaScript.
In order to use this dark mode in your next project, you will need to follow couple of the the steps below.
Step 1
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Toogle Animation Pure CSS - ramCoder</title><link rel="stylesheet" href="style.css" /></head><body><input type="checkbox" name="" id="" class="checkbox" /><script src="./app.js"></script></body></html>{codeBox}
Step 2
:root {--bg-color: rgb(7, 7, 31);--bg-checkbox-color: white;--bg-checkbox-checked: rgb(46, 196, 46);}[data-theme="dark"] {--bg-color: white;--bg-checkbox-color: rgb(7, 7, 31);}* {margin: 0;padding: 0;box-sizing: border-box;}body {height: 100vh;width: 100vw;display: flex;justify-content: center;align-items: center;background-color: var(--bg-color);}.checkbox {height: 80px;width: 200px;appearance: none;background-color: var(--bg-checkbox-color);border-radius: 50px;position: relative;transition: all 0.4s ease;cursor: pointer;}.checkbox:checked {background-color: var(--bg-checkbox-checked);}.checkbox::before {content: "";width: 80px;height: 80px;background-color: rgb(173, 205, 247);border-radius: 50%;position: absolute;top: 0;left: 0;transform: scale(1.1);transition: all 0.3s ease;}.checkbox:checked::before {left: calc(200px - 80px);}{codeBox}
Step 3
var themeSwitcher = document.querySelector(".checkbox");var currentTheme = localStorage.getItem("theme");if (currentTheme) {document.documentElement.setAttribute("data-theme", currentTheme);if (currentTheme === "dark") {themeSwitcher.checked = true;}}function switchTheme(e) {if (e.target.checked) {document.documentElement.setAttribute("data-theme", "dark");localStorage.setItem("theme", "dark");} else {document.documentElement.setAttribute("data-theme", "light");localStorage.setItem("theme", "light");}}themeSwitcher.addEventListener("change", switchTheme, false);{codeBox}
Congratulations, you just created an beautiful dark mode toggle in under 5 minutes. Now you can use this dark mode toggle in any of you future projects.