Search code examples
javascriptcssdom-eventsviewportsvg-animate

Trigger multiple svg line animations when in viewport


This jsfiddle https://jsfiddle.net/20zhrw1o/1/ shows how to trigger an svg line animation when it's in the viewport. I have that working on my (webflow) site. However, how do I go about if I have several svgs on one page which are not visible at the same time? At the moment only the first one is triggered.

Thanks in advance for any help!

Here's the javascript part, it toggles the css of the svg to start the animation.

var svg = document.querySelector('svg');

function isElementInViewport(el) {
  var rect = el.getBoundingClientRect();
  var isOutside = (rect.top >= window.innerHeight) || (rect.bottom <= 0);
  return !isOutside;
}

window.addEventListener('scroll', function(e) {
  svg.classList.toggle('in-view', isElementInViewport(svg));
});

Solution

  • Use document.querySelectorAll and loop through the NodeList returned:

    var svg = document.querySelectorAll('svg');
    
    function isElementInViewport(el) {
      var rect = el.getBoundingClientRect();
      var isOutside = (rect.top >= window.innerHeight) || (rect.bottom <= 0);
      return !isOutside;
    }
    
    window.addEventListener('scroll', function(e) {
      svg.forEach(function(el) {
        el.classList.toggle('in-view', isElementInViewport(el));
      });
    });
    

    Moreover, consider using IntersectionObserver that is considered way more performant that listening to scroll event.