en.javascript.info icon indicating copy to clipboard operation
en.javascript.info copied to clipboard

Intersection Observer API

Open enkeyz opened this issue 3 years ago • 5 comments

Hey!

Would be nice to see a topic about the Intersection Observer API: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

I used it one time, where I made a navbar sticky, whenever the user scrolling down and the hero section is no longer in the viewport. Example:

function stickyHeaderHandling() {
  const sectionHero = document.getElementById("hero-section");
  const navHeader = document.getElementById("nav-header");

  const stickyNav = function (entries) {
    const [entry] = entries;

    if (!entry.isIntersecting) {
      navHeader.classList.add("sticky--header");
    } else {
      navHeader.classList.remove("sticky--header");
    }
  };

  const heroObserver = new IntersectionObserver(stickyNav, {
    root: null,
    threshold: 0.1,
  });

  heroObserver.observe(sectionHero);
}

Also you can use it for lazy loading images, or animate html elements whenever the elements get into the viewport(https://www.itzami.com/blog/boost-your-css-animations-with-intersection-observer-api).

enkeyz avatar Feb 06 '22 12:02 enkeyz

This can also be implemented by the onscroll handler, right?

After a scroll, we check for positions and act, if needed.

iliakan avatar Feb 06 '22 17:02 iliakan

This one is completly replaces the old method, read the MDN docs I linked.

enkeyz avatar Feb 06 '22 17:02 enkeyz

I like the idea!

cesarkohl avatar Feb 19 '22 21:02 cesarkohl

Yes, I agree, it should be in the tutorial.

iliakan avatar Feb 20 '22 09:02 iliakan

As a hint, - there is a very compact Blog, that explains very well this powerful and easy "Intersection Observer" (... code and short video)

https://blog.webdevsimplified.com/2022-01/intersection-observer/

Thank you anyway for your phantastic Tutorial-Framework 😊

chkoeppel avatar Aug 27 '22 11:08 chkoeppel