I am trying to trigger the CSS animations of my page in the user's viewport only. Meaning the animation will start only once the element is visible. For that I decided to use the Intersection Observer but it only add my class to the first element with that class name, instead of all of them.
JS: .animate__animated has the 'animation-play-state: paused' property by default, and if the class is visible, it adds the 'is-running' class containing 'animation-play-state:running'. It works great with the first element, but not for the second (and others in my page).
How can I pass all the instances of that class into the entries? Can I even do that with the Intersection Observer? I am new to JS, I mostly follow tutorials online and can't seem to find a workaround.
const observer = new IntersectionObserver(entries => {
// Loop over the entries
entries.forEach(entry => {
// If the element is visible
if (entry.isIntersecting) {
// Set to animation-play-state: running
entry.target.classList.add('is-running');
}
});
});
observer.observe(document.querySelector('.animate__animated'));
CSS:
.animate__animated {
-webkit-animation-duration: 1s;
animation-duration: 1s;
-webkit-animation-duration: var(--animate-duration);
animation-duration: var(--animate-duration);
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
animation-play-state: paused;
}
.is-running {
animation-play-state: running;
}
Html:
<nav class="navbar has-text-white has-shadow" style="background:#231f20; max-height:80px;">
<div class="navbar-brand">
<a href="index.html" class="narvbar-item pl-2">
<img src="img/logo-txt.png" alt="Cheff Burgers Logo" class="pt-4 pl-5 animate__animated animate__lightSpeedInLeft" >
</a>
<a class="navbar-burger has-text-white" id="burger">
<span></span>
<span></span>
<span></span>
</a>
</div>
<div class="navbar-menu pb-5" id="nav-links" style="background-color:#231f20;">
<div class="navbar-end pr-6 mr-6 mt-5 animate__animated anim1 animate__lightSpeedInRight">
<a href="index.html" class="navbar-item has-text-white">Accueil</a>
<a href="menu.html" class="navbar-item has-text-white">Menu</a>
<a href="evenements.html" class="navbar-item has-text-white">Evènements</a>
<a href="contact.html" class="navbar-item has-text-white">Horaires & Contact</a>
</div>
</div>
</nav>