dimanche 24 avril 2022

Toggle class based on cookie and on toggle checkbox

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:

  1. On page load, it reads cookie, and if cookie value is true then it runs addClass. If cookie is false, then it runs removeClass.
  2. If the checkbox is manually checked, it runs addClass.
  3. If the checkbox is manually unchecked, it runs removeClass.
  4. When it is toggled, it needs to run the add or remove class immediately, not wait until after page load.

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?




Aucun commentaire:

Enregistrer un commentaire