Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

101
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda