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

94
Vistas
How to stop my eventlisteners from stacking in the body class?

I've written a code that instead of incorporating a light/dark mode, it incorporates a spring/summer/autumn/winter mode. Here is an example of one season:

const springThemeOn = sessionStorage.getItem("springtheme")
if (springThemeOn==="true"){
    document.body.className = "spring-theme";
    spring.classList.add('hide-icon');
    summer.classList.remove('hide-icon');
    autumn.classList.remove('hide-icon');
    winter.classList.remove('hide-icon');
}

//spring change
springIcon.addEventListener('click', () => {
    document.body.classList.toggle('spring-theme');
    spring.classList.toggle('show-icon');
    summer.classList.toggle('show-icon');
    autumn.classList.toggle('show-icon');
    winter.classList.toggle('show-icon');
    // Store toggle info between pages
    if (document.body.className.includes("spring-theme")){
        // Currently in spring mode
        sessionStorage.setItem("spring-theme", "true")
    } else {
        // Currently in other mode
        sessionStorage.setItem("spring-theme", "false")
    }
})

Imagine this with all four seasons. The code works, but when I click on each icon respectively, they each add themselves to the body class like so: <body class="b-page spring-theme summer-theme autumn-theme winter-theme"> and only displays the last clicked on mode.

I want to be able to switch through all four icons and not have to click on/off each icon in order to add/remove them from the class body. I do not want them to stack in the class body. Is there a fix for this? Thank you!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Instead of having a storage item for each theme, have them all share a single storage item.

const theme = sessionStorage.getItem("theme");
if (theme === 'spring') {
  // ...
} else if (theme === 'summer') {
  // ...
}
// etc

And in the click listener, something like:

if (document.body.className.includes("spring-theme")){
    sessionStorage.setItem('theme', ''); // remove any existing themes
} else {
    sessionStorage.setItem('theme', 'spring'); // add it
}

This way, there won't be any collisions.

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