I’m trying to toggle a class on my body tag while using a cookie to remember the users settings.
Using the jquery cookie plugin this is what i’ve come up with
$("a#switchit").click(function () {
if($.cookie('viewState')) {
$('body').addClass('light')
$.cookie('viewState', 'true', { expires: 9999 });
} else {
$('body').removeClass('light')
$.cookie('viewState', null);
};
});
I’m no expert in jquery so the syntax and everything is probably wrong, but hopefully you can see what i’m trying to achieve and set me right.
My html:
<a id="switchit">Switch it</a>
Based on your answer to my comment on the question, your issue is that you need to check for the presence of the cookie and set the class on page load as well as when the button is clicked.
To expand on this: A cookie will be persistent on page refresh (pending you’ve set the expiration for a suitable time frame) whereas any manipulations you make to the DOM (ie adding a class name to the body) will not persist.
You have it set up correctly for your user to select their color scheme and you are setting your cookie just fine. You just left out the part where you check in advance if they’ve set it on a previous visit.
So, in your jQuery ready function, add: