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

325
Vistas
Intersection observer - How do you remove a class after leaving the view port

I am adding a class when a div gets into the viewport using Intersection Observer. I just can't figure out how to remove the class when the div leaves the viewport. This is what I have so far:

const callback = function (entries) {
    entries.forEach(entry => {
        if(entry.isIntersecting)
        {
            entry.target.classList.add('animate1');
          observer.unobserve(entry.target)
          }
    });
}
const observer = new IntersectionObserver(callback);
const targets = document.querySelectorAll('.overlay');
targets.forEach(target => {
    observer.observe(target);
})

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Thank you for your help Randy. I did get it to work. Here is the final code:

const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    if (entry.intersectionRatio > 0) {
      entry.target.classList.add('animate1');
    }
    else {
      entry.target.classList.remove('animate1');
    }
  })
})
const boxElList = document.querySelectorAll('.overlay');
boxElList.forEach((el) => {
  observer.observe(el);
})
about 4 years ago · Santiago Trujillo Denunciar

0

instead of this

entries.forEach(entry => {
        if (entry.intersectionRatio > 0) {
          entry.target.classList.add('animate1');
        }
        else {
          entry.target.classList.remove('animate1');
        }
 })

you can use toggle() and instead of entry.intersectionRadio > 0 you can use entry.isIntersection

entries.forEach(entry => {
    entry.target.classList.toggle("animate1",entry.isIntersection)
  })
 
about 4 years ago · Santiago Trujillo 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