'multiple javascript observers for adding classes to multiple elements
I have a short javascript function which applies an animation class to a div when it is "scrolled" into view. This works great for one div with these classes. But how do I apply this to multiple elements with these classes? I have multiple elements of .square and .square-wrapper down the page, and I want each one to animate in when the user scrolls near it. Here is the function which only applies .square-animate to the first element :
<script>
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
const square = entry.target.querySelector('.square');
if (entry.isIntersecting) {
square.classList.add('square-animation');
return; // if we added the class, exit the function
}
// We're not intersecting, so remove the class!
square.classList.remove('square-animation');
});
});
observer.observe(document.querySelector('.square-wrapper'));
</script>
The HTML part looks something like this:
<div class="container row square-wrapper">
<div class="col s12 m4 square">
// some content here
</div>
</div>
<div class="container row square-wrapper">
<div class="col s12 m4 square">
// some content here
</div>
</div>
<div class="container row square-wrapper">
<div class="col s12 m4 square">
// some content here
</div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
