Simple Dark-Light theme with VanillaJs
Vaishnav
Posted on December 9, 2020
Dark mode designs and functionality that enable to toggle between Dark and Light theme is trending UI/UX Design๐ฅ. So, here's the guide to create Simple dark-light toggle.
I wanted this to be simple so I didn't create any fancy toggle switch just use simple button.
Codepen at end.๐ค
Let's Start with HTML
I'm using list for navbar elements, so
<li class="nav-item" id="toggle">๐</li>
and we are done with HTML. let's do CSS
CSS
// by default dark theme
:root {
--bg-color: #171923;
--bg-light: #232535;
--font-color: #c5cddb;
--font-light: #ffffff;
}
// light theme colors
.lightMode {
--bg-color: #E8E6DC;
--bg-light: #DCDACA;
--font-color: #3D3D3D;
--font-light: #202020;
}
lightMode
is class which would be added to body using js.
Final Part - Javascript
const toggle = document.querySelector("#toggle");
toggle.addEventListener("click", modeSwitch);
let isLight = true;
function modeSwitch() {
isLight = !isLight;
isLight ? toggle.innerText = "๐" : toggle.innerText = "๐";
var rootElement = document.body;
rootElement.classList.toggle("lightMode");
}
What is toggle?
- toggle is method of
DOMTokenList() interface.
- It remove token from token list and return false.
- If token doesn't exist, then it add token and return true.
What is happening?
When we click on toggle button, event listener respond to it and call modeSwitch()
function. In modeSwitch()
function, class lightMode
is added to body activating lightMode
color schema.
Contribution @casiimir
There are different ways to crate dark-light mode toggle. This one simple way I found out to explain how it work.
Love to here your suggestions and feedback๐คฉ.
Posted on December 9, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.