This is what Intersection Observer was made to do. With this you can watch elements and react when they come into view or intersect with each other.
First you set the options for the IO:
let options = {
rootMargin: '0px',
threshold: 1.0
}
let observer = new IntersectionObserver(callback, options);
If you leave out the root
option it wall default to your browser window, so once an element that you watch comes into viewport, the callback function gets triggered.
Then you specify which elements you want to observe:
let target = document.querySelector('.zoom');
observer.observe(target);
Here we now watch every element with the class zoom.
Last step is to define the callback function:
let callback = (entries, observer) => {
entries.forEach(entry => {
// Each entry describes an intersection change for one observed
// target element:
// like: $(element).addClass('zoom');
});
};
You can unobserve an element if you don't need it anymore, for example if you only want to play the zoom animation only once when it comes into view.
Also check out this example on how to change bg-color depending on how much of an element is visible on screen.
Edit: Maybe this example is more fitting (see comments) because it actually adds a class when user scrolls to the element.
Last point, you can use this polyfill from w3c to support older browsers.