Simple Dark-Light theme with VanillaJs

vaishnavs

Vaishnav

Posted on December 9, 2020

Simple Dark-Light theme with VanillaJs

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;
}
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

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๐Ÿคฉ.

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
vaishnavs
Vaishnav

Posted on December 9, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About