I set a cookie successfully in the browser, so that the cookie returned the cookie value true when checked, and false when unchecked. This cookie changes back and forth on every click of the checkbox.
Here's what I need to do:
true then it runs addClass. If cookie is false, then it runs removeClass.addClass.removeClass.Here's what I have, and no errors in console. It's working now, but there's a lag after the page load. How can I fix it to remove the lag?
var mytoggle = $.cookie('checkboxValue'); // gets the value saved
if(mytoggle && mytoggle === "true") // (sees if cookie exists and has value of true)
{
$('body').addClass("myclass");
} else // (if cookie doesn't exist or value is false)
{
$('body').removeClass("myclass");
}
Basically, it sees if there's a cookie with value of true, and if so then adds the class. But if there's no cookie or value is false, it removes the class. And if the checkbox is toggled while on the page, it adds or removes the class.
How can I get this to check the cookie and add or move class based on the cookie value, and also toggle the class when the checkbox is checked or unchecked?
Cookie is a string, not a boolean. So, you should use if (cookie === "true"). Also, you don't need to check for existence of cookie, it won't be equal to true if not exists.
P. S var keyword is legacy and considered as a bad practice. use let or const instead.