https://gomakethings.com/options-settings-and-approaches-with-the-vanilla-js-intersection-observer-api/

og.png

Yesterday, we learned how to use the Intersection Observer API. Today, I wanted to take a look at some options and settings you can use when setting up an observer, as well as two different approaches for observing multiple elements.

Let’s dig in.

Options and settings #

The Intersection Observer API has a few options and settings you can configure when setting up your observer. You can pass in an array of options (all of them optional) as the second argument on the new IntersectionObserver() constructor.

For example, let’s imagine that we wanted to lazy load text into our elements when they’re 150 pixels away from entering the viewport.

We would do this. For readability, lets also pull the callback function out into its own named function.

// Lazy load text
function loadText (entries, obs) {
	entries.forEach(function (entry) {

		// If the entry is not in the viewport, do nothing
		if (!entry.isIntersecting) return;

		// Stop observing
		obs.unobserve(entry.target);

		// Log the console when it happens
		console.log('Entered the viewport');

		// Add text
		entry.target.textContent += ' In the viewport now';

	});
}

// Setup our observer options
let options = {
	rootMargin: '150px'
};

// Create a new observer
let observer = new IntersectionObserver(loadText, options);

// The element to observe
let app = document.querySelector('#app');

// Attach it to the observer
observer.observe(app);

Observing multiple elements #

If you have multiple elements you want to observe, and want to run the same callback function on each of them, you can observe() multiple elements with the same Intersection Observer.

// Create a new observer
let observer = new IntersectionObserver(function (entries) {
	console.log(entries);
	entries.forEach(function (entry) {
		console.log(entry.target);
		console.log(entry.isIntersecting);
	});
});

// The elements to observe
let div1 = document.querySelector('#div-1');
let div2 = document.querySelector('#div-2');

// Attach them to the observer
observer.observe(div1);
observer.observe(div2);

With multiple elements being observed, the entries array may (or may not) contain multiple items.

If #div-1 and #div-2 are right next to each other, one may leave the viewport at the same time that the other enters. In that situation, the one leaving would be in the entries array with an isIntersecting value of false, while the one entering would have a value of true.

That said, only elements that have changed show up in the entries array.

If they weren’t near each other on the page, or if only one element’s intersection with the viewport changed, only that item would be in the entries array in the callback function.