DEV Community

Cover image for Intersection Observer API: you need it!
Luca
Luca

Posted on

9 2

Intersection Observer API: you need it!

Hi Dev!๐Ÿ™‹โ€โ™‚๏ธ

Today i want to talk you about the Intersection Observer API!
I'm in love whit this API, because it is simple to use and it is very usefully for your projects.

This is what you need:

Select you element: โ˜๏ธ

const elements = document.querySelectorAll('.elements');

Create a function and add/remove class when the element is visible or not inside the window: ๐Ÿ“ช๐Ÿ“ซ

function handleIntersection(entries) {
  entries.forEach((entry) => {
     if (entry.isIntersecting) {
       entry.target.classList.add('visible')
     } else {
       entry.target.classList.remove('visible')
     }
  });
}
Enter fullscreen mode Exit fullscreen mode

Create you variabile with the API and the function: ๐Ÿ

var observer = new IntersectionObserver(handleIntersection);
Enter fullscreen mode Exit fullscreen mode

Add the config: โœ๏ธ

var config = {
  root:null,
  rootMargin: '0px',
  threshold: 0 
}

var observer = new IntersectionObserver(handleIntersection, config);
Enter fullscreen mode Exit fullscreen mode

Observe all the elements: ๐Ÿง

elements.forEach(element => observer.observe(element));
Enter fullscreen mode Exit fullscreen mode

Every time the target is near the window, the observe api look for the elements and add/remove the class (in this case .visibile).

Thank you for read!๐Ÿง‘โ€๐Ÿ’ป

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Googleโ€™s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (1)

Collapse
 
dannyengelman profile image
Danny Engelman โ€ข

See the classList.toggle method

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started