How to make a website light/dark toggle with CSS & JS

Kevin Powell · 132K views · 2019 · 16:48

Open on YouTube

Web developmenttutorial

Why Stack Overflow recommends it

Stack Overflow users link it when someone asks how to add a dark or light mode switch that remembers the user's preference, and several people say they built their own code from it.

Recommended by 2 people across 2 different months, 2020 to 2022.

What it is

Kevin Powell walks through building a dark/light mode toggle for a website using CSS custom properties and a small amount of JavaScript. The toggle saves the visitor's choice in localStorage so it persists on later visits. It is a screen-recorded coding tutorial with a CodePen of the final code.

What people said

Recommends rishimaharaj · 2021-11 · Stack Overflow · on “How to enable light mode on my whole page?”

Kevin Powell has a great Dark Mode JavaScript toggle using localStorage [this video] tutorial that you can use for reference

Recommends RandomCoder · 2022-08 · Stack Overflow · on “Is it possible to make a dark/light mode button that changes the inner css colors on all pages?”

found a video [this video] and followed the steps, it required me to change a lot of my css into variables: :root { --color-purpe: #FFA14A; --color-purple-hov: #DE8430; --body-bgr: #2B3549; --h1-orange: #ffffff; --black-labels: #ffffff; --bas-orange: #7D63DE; --bas-org-hov: #7D63DE; --bas-red: #C34437; --bas-red-hov: #b03628; --disbaled: #a0a0a0; } .lightMode { --color-purpe: #7D63DE; --color-purple-hov: #7D63DE; --body-bgr: #ffffff; --h1-orange: #E18127; --black-labels: #000000; --bas-orange: #FFA14A; --bas-org-hov: #DE8430; --bas-red: #C34437; --bas-red-hov: #b03628; --disbaled: #a0a0a0; } and then I used this function to make it work: let lightMode = localStorage.getItem('lightMode'); const li

Cites Salamander Confucious · 2020-05 · Stack Overflow · on “Darkmode + Changing source of pictures”

So I had implement dark mode to my website but there are pictures that I need to change for it to function properly. I have the light and dark versions of the images that I need but I would like to know if there's any way I can change the source of the image when I enable dark mode. I got my code from this video: [this video] This is my button for darkmode and the image in HTML: <button onclick="changeImage();" id="dark-mode-toggle" class="dark-mode-toggle">Darkmode On/Off</button> The Javascript to enable darkmode (refer to youtube link above): let darkMode = localStorage.getItem('darkMode'); const darkModeToggle = document.querySelector('#dark-mode-toggle'); const enableDarkMode = () => { docum