hope you’re doing great.
I have a piece of javascript code that works great and the animations are starting to play only when the user scrolls down and the elements are into viewport.
However, the animations are playing only once.
How can i make the animations restart every time the user scrolls and they enter viewport ?
Big thank you in advance.
This is the JavaScript code that i have so far, working by only triggering the animations once, when they enter viewport first time.
var observer = new IntersectionObserver(function(entries) {
entries.forEach(function(element) {
if(element.isIntersecting === true){
element.target.classList.add("play-animation");
/*
* optional: By callsing the 'unobserve' the element gets removed from the observer
* (by doing this, if the element is scrolled out of view and back into view after, nothing will happenn)
*/
observer.unobserve(element.target);
}
});
}, { threshold: [0] });
observer.observe(document.querySelector('.progress-ai'));
observer.observe(document.querySelector('.progress-dw'));
observer.observe(document.querySelector('.progress-ps'));
observer.observe(document.querySelector('.progress-ae'));
observer.observe(document.querySelector('.progress-xd'));
observer.observe(document.querySelector('.progress-id'));
>Solution :
Don’t unobserve the elements whenever they leave the view. Instead add an else statement where the animation class is removed whenever the element isn’t intersecting.
const observer = new IntersectionObserver(function(entries) {
entries.forEach(function(element) {
if(element.isIntersecting === true) {
element.target.classList.add("play-animation");
} else {
element.target.classList.remove("play-animation");
}
});
}, { threshold: [0] });
const elements = document.querySelectorAll('.progress-ai, .progress-dw, .progress-ps, .progress-ae, .progress-xd, .progress-id');
for (const element of elements) {
observer.observe(element);
}