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')
}
});
}
Create you variabile with the API and the function: ๐
var observer = new IntersectionObserver(handleIntersection);
Add the config: โ๏ธ
var config = {
root:null,
rootMargin: '0px',
threshold: 0
}
var observer = new IntersectionObserver(handleIntersection, config);
Observe all the elements: ๐ง
elements.forEach(element => observer.observe(element));
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!๐งโ๐ป
Top comments (1)
See the classList.toggle method