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🤩.
Top comments (17)
Nice done, I love it!
Can I suggest three more lines of javascript? :D
The ternary expression can be simplified to the following:
Hey. I updated pen according to your suggestions. Thanks 🤩.
Really? I'm honored! :D
Yep. I'm still learning and I love to share what learned hoping it would be helpful for someone.😄
Me too, same story!
Nice website, I like it. Do you like something about my repos? :D
I checked repos... You have awesome portfolio 🔥.
I really appreciate it! :D
Great nice and lightweight.
Nice! I’ll try using this in my next project ;D
How do we put animation like the thumbnail of this post??
Here codepen you can refer.
codepen.io/demilad/pen/bZRjpb
Toggle switch can be customised using CSS
Thank you very much
Be aware that internet explorer doesn't support css variables
Hey Thanks, I didn't know about it.
Great job!
nice! In future i am going to use this.