I want to trigger CSS animations in a horizontal layout, only when the animated element gets in the viewport. I would also like to have them triggered every time they come into the viewport, not just once.
The JavaScript Intersection Observer API can watch for elements positions in any scroll direction, can perform actions on them when they enter/leave the viewport, and can repeat those actions each time these events happen. It is very efficient and well-supported. Here is a basic example:
// Get an array of elements to watch
let elements = document.querySelectorAll('.foo');
// Set an observer to watch their position relative to the viewport boundaries
let observer = new IntersectionObserver(function (entries, self) {
entries.forEach(entry => {
// If this item is in the viewport
if (entry.isIntersecting) {
// Do some code on that item
entry.target.classList.toggle('animated');
}
});
}, { rootMargin: '0px 0px 0px 0px' });
// Tell each element to be watched
elements.forEach(el => {
observer.observe(el);
});