Appearance on scroll with the Intersection Observer API
You have surely several times seen sites with sections come to life when you scroll. This little artistic touch (obviously it's art… of dev) is possible thanks to this nice API called Intersection Observer.
Let's imagine a simple page with several sections:
<body>
<h1>Intersect Observer API</h1>
<section>Section</section>
<section>Section</section>
<section>Section</section>
<section>Section</section>
<section>Section</section>
<section>Section</section>
<section>Section</section>
</body>
In our JS, we will do it this way:
We first initialize our sections (in ES6 here)
const targets = document.querySelectorAll ('section');
Then we initialize a new IntersectionObserver object with a callback like this:
const observer = new IntersectionObserver (handleIntersection);
If I only had one section, then I would just have to do:
observe.observe (targets);
Having multiple sections, I have to loop over them like this:
targets.forEach(target => observer.observe(target));
As you can see, the key element is the function observed
which allows to observe in real time that the target appear on the screen. A bit like the watch
for amateurs.
Here is the final result:
For information about this API, I suggest you go to the DND site to read the full doc: MDN Web Docs