• Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

204
Views
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);
})

9 months ago · Santiago Trujillo
2 answers
Answer question

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);
})
9 months ago · Santiago Trujillo Report

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)
  })
 
9 months ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.