How To Stop Light Mode Flickering To Darker Background On Page Load
So I have a bit of script for toggling between light and dark modes on my site. The dark mode is the default. Problem is, whenever the light mode is toggled on, with every page loa
Solution 1:
Put your JS (the part reading from local storage and applying the class) in the <head>
section, and add the class to the <html>
tag, so that it get executed before the body
is parsed and displayed.
You can try it with this simple working demo:
<html><head><script>// Do this before the body gets parsedif (localStorage.getItem('darkmode') === '1') {
document.documentElement.classList.add('darkmode');
}
</script><style>.darkmodebody { background: #222; }
.darkmode.light-only { display: none; }
html:not(.darkmode) .dark-only { display: none; }
</style></head><body><buttonid="darkToggle">
Switch to
<spanclass="dark-only">light</span><spanclass="light-only">dark</span>
mode
</button><script>document.querySelector('#darkToggle').addEventListener('click', function() {
var wasDarkMode = localStorage.getItem('darkmode') === '1';
localStorage.setItem('darkmode', wasDarkMode ? '0' : '1');
document.documentElement.classList[wasDarkMode ? 'remove' : 'add']('darkmode');
});
</script></body></html>
Post a Comment for "How To Stop Light Mode Flickering To Darker Background On Page Load"