M.dev()

Intersection Observer API

Intersection Observer API

25.02.2022

Javascript

The Intersection Observer API is a very neat and clean way to handle stuff only after is shown on the screen. It can be used for lazy loading of images of handle same animation after the element is in the view port.

Lazy loading:

1const imgs = document.querySelectorAll("img"); 2 3const imgObserver = new IntersectionObserver( 4 (entries, observer) => { 5 entries.map(entry => { 6 if (entry.isIntersecting) { 7 const dataSrc = entry.target.dataset.src; 8 if (dataSrc) { 9 entry.target.src = dataSrc;//set src from dataset 10 if (dataSrc) { 11 } 12 observer.unobserve(entry.target); //after we are done we no longer need to observe it. 13 } 14 }); 15 }, 16 { rootMargin: "0px", threshold: 0 } 17); 18imgs.forEach(img => imgObserver.observe(img)); 19

Animation:

1const img = document.querySelector("img") 2 3const callback = (entries, observer) => { 4 entries.forEach((entry) => { 5 if (entry.isIntersecting) { 6 entry.target.classList.add(".animation") 7 }else { 8 entry.target.classList.remove(".animation") 9 } 10 }) 11} 12 13const myObserver = new IntersectionObserver(callback, {}) 14 15myObserver.observe(img) 16

In this example, we don't use unobserve, so the every time element goes in viewport will trigger the animation.

Intersection Observer API simpifies all tasks which includes position ralative to viewport, no need of caluculations.