mGryska
mGryska

Reputation: 33

Intersection Observer not working below 600px viewport (+GSAP)

A have problem with my content animation. Everything working fine, but when I make responsive website and make viewport width below 600px, my intersection Observer not working. Nothing happen.

I add console.log to IO and nothing show up in console, when I scroll my website. When I scroll when width is more than 600px, I can see IO in console.

Maybe someone know solution for this problem?

My code:

//global
const slideDuration = 1;

// scroll animation
let target = document.querySelectorAll("section");
const options = {
 root: null,
 threshold: 0,
 rootMargin: "-300px"
};

const contentAnimation = (left, right) => {
  gsap
    .timeline()
    .from(right, { opacity: 0, duration: slideDuration, x: 400 })
    .from(left, { opacity: 0, duration: slideDuration, x: -400 }, "-=0.5");
};

 const io = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
  //show content
  const getElement = entry.target.className;
  const contentElement = document.querySelector(`.${getElement}__content`);
  contentElement.style.opacity = "1";

  //animation
  const right = document.querySelectorAll(`.${entry.target.className}-right`);
  const left = document.querySelectorAll(`.${entry.target.className}-left`);

  contentAnimation(left, right);
  io.unobserve(entry.target);
}
  });
}, options);

target.forEach(section => {
  io.observe(section);
});

Upvotes: 2

Views: 2884

Answers (1)

Zach Saucier
Zach Saucier

Reputation: 25984

You have rootMargin: "-300px". This means that intersecting won't start until you're 300px in on any side. When the viewport is less than 600px, there's no more element to intersect with, hence it not working.

See the intersection observer docs for more info.

Upvotes: 2

Related Questions