Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 9, 2020 12:59 pm GMT

Simple Dark-Light toggle 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);function modeSwitch() {  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.

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.


Original Link: https://dev.to/vaishnavme/simple-dark-light-toggle-with-vanillajs-2cbj

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To