Search code examples
javascriptcssintersection-observer

Elements jumping on the screen non-stop, when element is on the edge of being in intersection (Intersection Observer)


I have a page with a sticky footer with stacked buttons, when the footer is not entirely on viewport I hide one of the buttons, when the footer is in place I show the buttons, the problem is when the container is on the edge, because then it starts flickering.

it flickers because the container gets bigger as we add the second button (when it enters fully viewport), and because it gets bigger, it makes the container not be fully visible again.

Is there a way to go around it? I've added a gif and a codepen to the issue.

https://codepen.io/felipefernand3s/pen/OJGgMOK

I just want to have a footer with stacked buttons, the footer and one of the buttons are always visible, but when the footer is pinned (it means it's in it's correct html place instead of "floating", I want to show all stacked buttons.

const el = document.querySelector(".myElement")
const observer = new IntersectionObserver( 
  ([e]) => e.target.classList.toggle("is-pinned", e.intersectionRatio < 1) || console.log(e.intersectionRatio),
  { threshold: [0] }
);

observer.observe(el);


Solution

  • Well, the way to make it work is adding a element on top of the one we want to observe.

    https://codepen.io/felipefernand3s/pen/OJGgMOK


    If you want to see the error happening, just change the element observed from flag to el - and then scrolls down.