Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Re-triggering animations every time they enter viewport

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'));

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading