Intersection Observer API
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).
This can also be implemented by the onscroll handler, right?
After a scroll, we check for positions and act, if needed.
This one is completly replaces the old method, read the MDN docs I linked.
I like the idea!
Yes, I agree, it should be in the tutorial.
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 😊