Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!