dyc
dyc

Reputation: 15

Toggle active class using Intersection Observer

I'm trying to change the active class of my sections when scrolling through the page. I'm using the intersectionObserver, but am feeling rather stuck with it. I need to get the activeElement from the activeId but am not sure how to do this.

This is de code I've got:

const options = {
    threshold: 0.75
}

let observer = new IntersectionObserver(check, options);

function check(entries) {
    entries.forEach(entry => {
        const activeId = entry.target.id;
        const activeElement = 

    if(entry.isIntersecting){
        activeElement.classList.toggle("your-active-class");
    };
});
};

sections.forEach(section => {
    observer.observe(section);
});

Upvotes: 1

Views: 1899

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206488

  • Use entry.isIntersecting directly for your classList.toggle() second (boolean) argument.
  • Use options {threshold: 0}, or don't use at all, since threshold defaults to 0

const check = (entries) => entries.forEach(entry => {
  entry.target.classList.toggle("is-active", entry.isIntersecting);
});

const Obs = new IntersectionObserver(check);
document.querySelectorAll("section").forEach(el => Obs.observe(el));
* {margin:0; box-sizing: border-box;}

section {
  min-height: 100vh;
  transition: 0.5s;
  transform: scale(0.4);
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 70vh;
}

.is-active {
  transform: scale(1);
}
<section style="background: #0bf;">1</section>
<section style="background: #f0b;">2</section>
<section style="background: #fb0;">3</section>
<section style="background: #0fb;">4</section>

Upvotes: 2

Related Questions