Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 21, 2022 07:06 pm GMT

A guide to Intersection Observer

Atsome point during your frontend career, you probably had toorwantedto, figure out where anelement isrelated tothe scrolling position ofthe user. Ifnot, dont worry, Ibelieve this will still beinteresting toyou, because itmight pop some ideas and give you inspiration for your projects. Today, wewill gothrough the Intersection Observer API aneasy way todetermine whether the DOM element somehow intersects with the viewport, oranother element.

Why Intersection Observer?

Throughout the frontend history, detecting when something isintersecting with another thing was tricky. Often, hand-crafted solutions were unreliable, tothe point itcaused some visible impact onusers browsers and websites. Today, weare lucky tohave the Intersection Observer API, but why? What were the main drivers behind this development? Lets look atsome examples ofhow things were done before.

The lazy loading technique isone example ofwhere developers want toknow when aDOM element isentering the viewport. Tolazy load animage, you have toknow whether auser isrelatively close tothe image position onthe page asthey are scrolling. You could achieve this byhooking upthe scroll event, and calling getBoundingClientRect method.

The getBoundingClientRect would return anobject providing information about the size ofanelement and its position relative tothe viewport. Then, you could figure out whether totrigger the download ofthe image your user wants tosee. Or, you could trigger arequest tonotify that the user just viewed animage orspecific element onthe page.

This solution was used over and over inthe past. However, this solution was often sluggish because calling getBoundingClientRect forces areflow ofthe page. The reflow isaprocess when the browser needs tore-calculate the position, and dimensions ofthe elements onthe page. Ifcalled often, browsers and computers can only take somuch heat, and will eventually start tobecome laggy.

Heres asmall Codepen example ofhow you can tap into the scroll listener and get the data about the desired element:

For this exact reason, the Intersection Observer API was introduced inChrome51. What makes this API better than the approach with the getBoundingClientRect, isthat itprovides away toasynchronously observe changes inthe intersection ofatarget element with another element. That way, when you use Intersection Observer, youre not stressing the browser and the page, asmuch asyou are with the getBoundingClientRect approach.

Awesome, now that wewent through the backstory ofhow Intersection Observer came tobe, lets dive inand see how wecan use itproperly.

How touse the Intersection Observer?

Toget the best idea ofhow touse anintersection observer, lets dive right into how tocall itincode:

const options = {  root: document.getElementById('some-id'),  rootMargin: '0px',  threshold: 1.0,};const observer = new IntersectionObserver(callback, options);

The IntersectionObserver constructor receives two arguments:

  • callback acallback function that gets called whenever athreshold iscrossed inany direction.

  • options anobject with additional configuration.

The options object contains following fields:

  • root itpinpoints anelement that serves asaviewport, and must beanancestor ofthe target element (wewill show later how totarget anelement). Ifyou leave this option out, the observer will default tothe browser viewport.

  • rootMargin ittells the observer when totrigger the intersection between the root and the target element. Here, you can put values like you usually dofor amargin inCSS.

  • threshold this can beasingle number, orarray ofnumbers. The threshold indicates atwhat percentage ofthe target elements visibility you want the provided callback toget called. So, ifyou want tolazy load animage only when auser scrolls25% ofit, then you can put the value of 0.25 there. Ifyou want some logic tobetriggered, both at25% and50% ofvisibility ofthe target, then you put [0.25, 0.5] array here.

Cool, now weknow what the constructor receives, but how doweactually target anelement tobeobserved? Lets find out through anexample:

const target = document.getElementById('target-element');observer.observe(target);

Nice, now when our element with the ID target-element intersects with the root element weset, the callback will get called. Naturally, weshould look into how towrite aproper callback for the Intersection Observer:

const intersectionCallback = (entries, observer) => {  entries.forEach(entry => {    // you can find out easily if target is intersecting by inspecting `isIntersecting` property    if (entry.isIntersecting) {      console.log(`Hey, I'm intersecting`)    }  });}

The callback receives alist ofentries that areof IntersectionObserverEntry type. Having alist asthe first argument means that one observer can observe multiple target elements. Each entry has aset offields, but one thats most often used isthe isIntersecting. Inthe example above, welog tothe browser console whenever our target isintersected.

The second argument passed tothe callback isthe observer itself. This can beuseful when you want tostop observing the target after anintersection then you call observer.unobserve() inthe callback.

Great, now that wewent through some basics onusing the Intersection Observer, lets put ittouse and build something.

Using Intersection Observer

Lets build aworking example where avideo starts playing asyou scroll intoit, and itpauses asyou scroll away. Toachieve this, well use the powerful Intersection Observer wejust showcased inthe section above.

Tostart off, well need avideo inside HTML. Iwill share the important HTML, and fullJS code ifyou want totry itout. There will also beaninteractive demo you can try out atthe bottom. Heres the simplified HTML:

<video muted controls>  <source    src="https://ucarecdn.com/33fa1b5d-a164-4178-908c-5a51f872fcef/video.webm"    type="video/webm"  />  <source    src="https://ucarecdn.com/1b63a65c-7796-4b23-a6fc-bb751f1221ed/video.ogg"    type="video/ogg"  />  <source    src="https://ucarecdn.com/ec3f39c9-be9f-4231-a4db-d7fcbd209e71/video.mp4"    type="video/mp4"  /></video>

Inthe HTMLwe simply put a video tag with several sources. And, finally, our Intersection Observer code:

let video = document.querySelector('video');let observer = new IntersectionObserver(  (entries, observer) => {    entries.forEach((entry) => {      if (entry.intersectionRatio !== 1 && !video.paused) {        video.pause();      } else {        video.play();      }    });  },  { threshold: 1 });observer.observe(video);

Here, weare getting the video element using document.querySelector('video'). Then, wedefine our Intersection Observer instance with acallback and athreshold of 1. The threshold of 1 means that our callback will trigger when the video isfully visible, oritstops being fully visible.

Inour callback, wecheck whether the video isnot fully visible, with the entry.intersectionRatio !== 1 check. The intersectionRatio indicates which portion ofthe element isvisible, and itgoes from 0to1 where 1means itisfully visible. Everything between 0and 0.99 means that the element, video element inour case, ishidden abit. There, wealso check whether the video ispaused. Ifthe video isplaying and itishidden abit wepauseit.

Now, ifthe videos intersectionRatio is1, wefall into the else branch and weplay the video.

This isacool trick you can try out onyour project. Itdoesnt require alot ofcode, and can beagood user experience. But remember tonot autoplay videos bydefault itcan beannoying tousers. Heres ademo you can play around with:

Summing up

Ihope you had agreat time reading, and trying out the Intersection Observer API. Ifyou learned athing ortwo, thenI call this blog post asuccess. Lets goover the things welearned today:

  1. Intersection Observer can beused todetect intersections between elements, orbetween anelement and the viewport.

  2. You use the API byinstantiating the observer with new IntersectionObserver(callback, options).

  3. The callback parameter isamethod that receives anarray ofentries, and the observer itself.

  4. The options parameter isanobject that can consist of root, rootMargin, and threshold properties. This parameter isoptional.

  5. The instantiated observer can observe anelement you pass toitwith observer.observe(element).

Thats it! Youve learned the basics. Ifyoure looking for something more advanced, you can always play around with the threshold option that Intersection Observer receives. Or, you can dabble with the IntersectionObserverEntry object for extra information when the intersection happens. Ifwetried tocover that, this blog post would bealengthy one, sowewill save itfor another time.

Until then, thanks for reading, and catch you inthe next one.

Originally published by Nikola uza in Uploadcare Blog


Original Link: https://dev.to/uploadcare/a-guide-to-intersection-observer-517p

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To