I have implemented a dark mode to a WordPress site using a simple technique like this one found in https://github.com/avecNava/dark-mode.
<script>
//runs on every page load, checks local storage for last mode and applies dark mode if found
document.body.classList.toggle('dark-mode', localStorage.getItem('darkmode') === 'true');
//the function must be called when dark mode is clicked by the user
function switch_mode(){
const dark = localStorage.getItem('darkmode') === 'true';
localStorage.setItem('darkmode', !dark);
const element = document.body;
element.classList.toggle('dark-mode', !dark);
}
To prevent flickering I've tried to place the first row inside the head tags (via header and footer scripts plugin) but it doesn't seem to work. I've seen solutions to this problem but they all seem to be built different from the start so it's hard to apply those solutions to the code I'm using.
To trigger the switch, I'm using a clickable icon that has an onClick() property that calls the function. Is there any solution to my problem or should I just start the whole thing from scratch using a different technique for example a checkbox trigger?