An Interest In:
Web News this Week
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
- March 14, 2024
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;}
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");}
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
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To