I want to create a toggle function for my localStorage as I am trying to install a dark mode on my site and I want it to remember the user's choice.
I want it load the current preference on page load, if one has been made, and then toggle the state on click. My code is below - however I am clearly making some error on my attempt to toggle the localStorage state.
// ON PAGE LOAD, IF USER PREFERS DARK, ADD DARK CLASS TO HTML
if (window.localStorage.getItem('preferDark')) {
$('html').toggleClass('dark');
}
// TOGGLE STATE ON CLICK
$('.wrapper').click(function(){
if (window.localStorage.getItem('preferDark', true)) {
window.localStorage.setItem('preferDark', false);
} else {
window.localStorage.setItem('preferDark', true);
}
$('html').toggleClass('dark');
});
I know there are various localStorage toggle questions out there but I can't find one quite the same as mine.