DEV Community

Lens
Lens

Posted on • Updated on

How IntersectionObserver works

Introduction

IntersectionObserver is a Javascript API and is one of the three observer API’s. In web development it’s used to add scroll animations or infinite scrolling like on the github copilot page or on this webpage i made. So here we’ll learn how it works and how to use it. I made this explanation based on what i learned last week, but go to the bottom to see where you can be explained more! I made this as informative as possible so i hope you like it.

How to make it

To make it you first need to make a const variable (usually called observer) that has new IntersectionObserver()and inside it’s constructor (which are the parentheses after it) you add either an arrow function or a normal function where you put what happends when something intersects the viewpoint. That something is re-typed as the entries parameter, the only argument any function inside the constructor accepts. So then how do you observe something? You have to use the observe() method and in it call an element or a variable with an element that you want to observe. Inside the function if you want to observe multiple elements then you use the forEach() to target each entry that’s observed.

//arrow function version (you'll see it be used the most)
const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {//where you put the wanted action for when it's observed});
});

observer.observe(//element you want to observe);
Enter fullscreen mode Exit fullscreen mode
//normal function version
const observer = 
new IntersectionObserver(function(entries, observer) {});

observer.observe(//element you want to observe);
Enter fullscreen mode Exit fullscreen mode

Tip: If you want more details about what you’re observing give the function in the IntersectionObserver console.log(entries) then go to your console console where you’ll find information about how it’s being observed.

How to Use it

This may seem useless for some people, but with this API you can be creative with your webpage and how it works. For example, on the code from the webpage i made you can see that i gave each element a hidden class that makes them invisile and far off the webpage but i made a show class had the opisite of what it had. I used IntersectionObsever so when any element with the hidden class intersects the viewpoint it gets the show class which makes a cool transition. This is just one of the many ways you can combine this with CSS to make cool transitions. You could also make some for color, shape, size, and more! (Make shure to click the HTML, CSS, and Javascript buttons to see how it works. Especially the javascript!)

Result

scroll down to see the scroll animations!

Threshold

The Threshold property is used put how much of an element intersects to trigger the observer action. It's value is between 0 and 1 which is the same as 0%-100%. It's default value is 0 wich means as soon as a single pixel of an observed element intersects an action made in the constructor will happen. 1 on the other hand means if the element is fully intersecting with the viewpoint then an action will happen.

Say that you were editing my javascript codepen by adding a threshold property to it (you can do it right now by clicking edit on codepen that on the codepen embed). Inside the IntersectionObserver function you add a threshold that has the value of 0.5. This means that the elements it's observing will be affected if half of it is intersecting.

To add it to the observer API you have to put it as the last parameter in the constructor. Don't be fooled by seeing how long your functions are! Everything is in the observer constructor including the functions so after you make the functon you simply add it after. If it's still confusing for you here's an example.

Here it is without any content in the arrow function, as you can see the threshold is simply just a parameter

const hiddenElements = document.querySelectorAll(".hidden");

const observer = 
new IntersectionObserver((entries) => {}, {threshold: 1 });

hiddenElements.forEach((el) => observer.observe(el));
Enter fullscreen mode Exit fullscreen mode

Now here it is with the content, the threshold is still the last parameter even though the content in the arrow function makes it seems totally diffent. This might cause you to put you threshold in the wrong place

const hiddenElements = document.querySelectorAll(".hidden");

const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
    console.log(entry);
     if (entry.isIntersecting) {
        entry.target.classList.add('show');
     }
     else  {
        entry.target.classList.remove('show');
     }
    });
}, {threshold: 1 });

hiddenElements.forEach((el) => observer.observe(el));
Enter fullscreen mode Exit fullscreen mode

(put a threshold on my codepen and notice how the images take longer scrolling to see, for some reason you might not see the text which is a bug i'll fix later)

Root Margin

The rootMargin option property is similar to the CSS margin except it changes the size of the viewport. You can put up to 4 values but unlike the CSS margin you have to put a px on even the value of 0. It also has to be a string unlike the threshold property. If you want to make it bigger than the normal size you have to use positive values while if you want to make it smaller than the normal size you use a negative value.

const observer = 
new IntersectionObserver((entries) => {}, {rootMargin: 1 });
Enter fullscreen mode Exit fullscreen mode

Root

The root property is used to set the boundry of the viewpoint as the size of an element. It has to be one of the elements that is being observed. It can be useful for stuff like scroll containers.

const observer = 
new IntersectionObserver((entries) => {}, {root: document.body });
Enter fullscreen mode Exit fullscreen mode

Unobserve

The unobserve() method is used to stop the IntersectionObserver from observing an element when it's already been observed. For lazy loading images this can stop many issues and bug's. If we used this on my codepen after the the scroll animation happened once it would never happen again (unless the else conditional is still there).


const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
    console.log(entry);
     if (entry.isIntersecting) {
        entry.target.classList.add('show');
        observer.unobserve(entry.target.classList);
     }
     else  {
        entry.target.classList.remove('show');
     }
    });
}, {threshold: 1 });
Enter fullscreen mode Exit fullscreen mode

Disconnect

The disconnect() method is similar to unobserve except it causes all the targeted and selected elements to be unobserved. You simply type disconnect().

To Learn More About This:

videos:


Websites:
IntersectionObserver on mozilla
An Explanation of How the Intersection Observer Watches

Try It Yourself!

To know how to code something you also need to know how to make it yourself from experiance. So how about you make a nice project. My suggestion is to make an infinite scroll website or some scroll animations like the one i made. If you don't have any ideas here's one to make.

  • Make a webpage that's 4000px long
  • When at the bottom a div box with the text "Boo!" appears
  • (The transition from it going from invisible to visible should be 4 seconds)
  • Hint: use IntersectionObserver by putting conditionals that add and and remove a classlist. It should be a classlist that makes

Oldest comments (0)