IntersectionObserver - Observes HTML elements when they are visible via JavaScript scrolling.
I'm going to explain a very interesting method known as Intersection Observer in JavaScript. Basically, it allows me to implement this type of behavior: adding an observable to a list of IDs in a viewport and marking a link as activated based on a title visible in the viewport.
How does Intersection Observer work?
For this, the syntax is as follows:
Define the visibility threshold:
In my case, I consider it observable when at least 60% of the content is visible in the viewport:
const observerOptions = {
rootMargin: '0px 0px -60% 0px', // Detectar cuando el título está más arriba
};
You can adjust this value to what works best for you.
Select the elements to observe:
const headings = Array.from(document.querySelectorAll('.post h2, .post h3'));
In my HTML document (for example, in a post), I want to observe the h2 and h3 elements.
That is, when one of those headings reaches 60% visibility, the desired code is executed.
Before using it, we need to register the observer. For now, we've only defined:
headings.forEach(h => observer.observe(h));
Then, we loop through those elements with a forEach and apply .observe() to start monitoring them:
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const id = entry.target.id;
// Marcar el enlace activo
this.hxs.forEach(link => {
if (link.id === `${id}`) {
// TO DO
}
});
}
});
}, observerOptions);
In my case:
- I check if there are any entries in the entries array.
- If there are, I get the title's ID.
- With that ID, I do whatever I need.
I agree to receive announcements of interest about this Blog.
"What is IntersectionObserver in JavaScript? Explained clearly," Smart Scrolling, The API that will change the way you scroll the web.