DEV Community

Cover image for Did you know this JavaScript API?
Mohammed Farmaan.
Mohammed Farmaan.

Posted on • Updated on

Did you know this JavaScript API?

JavaScript's onscroll event is great, but how many of you have got bored of it trying to implement Lazy Loading or styling the Navbar on scroll while making a pixel perfect website?

Telling the browser to constantly look for scroll changes might be bad for a site's performance cause the browser never stops looking for scroll changes. So what is the alternative?

This, right here:

The Intersection Observer API

This API is great for implementing the features such as Lazy Loading or Changing backgrounds on scroll. And this API is actually very easy to use without putting much effort and counting pixels.

Here's how it works:

The Intersection Observer API takes a single or multiple elements which of course you can iterate over each one of them, and it observes for it to intersect with the viewport. As soon as the element intersects with the viewport, the callback function is executed and the required task is done. Below is a demonstration showing how it works in action:
Scroll to see the changes:

Live Demo:
https://zxcodes.github.io/JavaScript-Intersection-Observer-API/

Link to the repo:

GitHub logo zxcodes / JavaScript-Intersection-Observer-API

This example shows the working of Intersection Observer API on scroll.

JavaScript Intersection Observer API

This example shows the working of Intersection Observer API. Click the link for live demo. first second




Thanks for reading. Hope you like this. Have a great day!

Top comments (0)