Search code examples
javascriptsvgcss-animationsscrollreveal.js

Trigger svg line animation on screen view and reset it off screen view


here's a jsfiddle :

https://jsfiddle.net/20zhrw1o/

As the title says, I want to trigger the lines animation on when in screen view and reset it so that if i scroll back to it the animation starts again, I'm not good at js so thanks for any kind help!

also is it possible doing this with scrollreveal plugin?


Solution

  • CSS animations are hard to control directly through JavaScript (https://css-tricks.com/restart-css-animation/), so it's better to add and remove CSS classes to start/reset the animation.

    path {
        stroke: #000;
        stroke-width:2px;
        stroke-dasharray: 1000;
        stroke-dashoffset: 1000;
    }
    svg.in-view path {  
        animation: dash 20s linear forwards;
    }
    

    On every scroll event, see if the SVG is on-screen:

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

    https://jsfiddle.net/20zhrw1o/1/