I would like to add a button for switching to darkmode and lightmode on my website.
I use var()’s in my css to control the color of my elements.
This is my code:
function loadMode() {
const mode = localStorage.getItem('mode');
if (mode === 'dark') {
setDarkMode();
}
}
// set darkmode
function setDarkMode() {
document.documentElement.style.setProperty('--textColor', '#eaeaea');
document.documentElement.style.setProperty('--backgroundColor', '#333333');
document.getElementById('toggleMode').textContent = 'Wechsel zu Lightmode';
localStorage.setItem('mode', 'dark');
}
// set lightmode
function setLightMode() {
document.documentElement.style.setProperty('--textColor', '#313131');
document.documentElement.style.setProperty('--backgroundColor', '#e0e0e0');
document.getElementById('toggleMode').textContent = 'Wechsel zu Darkmode';
localStorage.setItem('mode', 'light');
}
// toggle the color mode
function toggleMode() {
const isDarkMode = localStorage.getItem('mode') === 'dark';
if (isDarkMode) {
setLightMode();
} else {
setDarkMode();
}
}
// event listener for button
document.getElementById('toggleMode').addEventListener('click', toggleMode);
// load mode on site load
loadMode();
This script is loaded on the end of the webpage (this is the problem, I know, but how can I fix it?)
Now I have the problem that every time I go to a subpage the website is being loaded with the Light Colors and then switched to the dark colors which results in a quick, but very annoying color flicker effect.
How can I prevent this form happening? My website is build with php so sessions could work? Or cookies?
Thank you for helping!
I tried to put the function in the header but then the body element cant receive the color change because I think its not loaded yes(?)
2
Answers
I fixed it myself:
Put part of the script in the :
And put the rest of the code at the end of the body:
Make sure that your JavaScript is executed as soon as possible. It is always a good idea to have you JavaScript defined in the
<head>
element. You can add the defer attribute to the script tag to make sure that the code is executed before theDOMContentLoaded
event. But having the inline JavaScript in the<head>
will also do that.The event
DOMContentLoaded
is fired when the DOM is ready and you can start manipulating the DOM. When that happens you can set the (dark/light) mode. In the following example I removed a lot of the JavaScript. The less you manipulate the DOM, the better. And I rely on CSS to switch between the two different modes.In the example I comment out the code for localStorage, because it doesn’t work on StackOverflow.