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:
zxcodes / JavaScript-Intersection-Observer-API
This example shows the working of Intersection Observer API on scroll.
Thanks for reading. Hope you like this. Have a great day!
Top comments (0)