Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

328
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda