Toggling localStorage item
Posted: 16 Nov 2020, 15:17
I want to create a toggle function for my localStorage where 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, but it's not working.
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, but it's not working.
Code: Select all
// 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');
});