JSFiddle - React, Tailwind, and code Playground

by silviagreen

HTML

<svg version="1.1" id="line" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="100px" height="20px" xml:space="preserve">
 <path class="line-delay" fill="none" stroke="black" stroke-width="1" stroke-dasharray="10,10" d="M5 10 l200 0"></path>
</svg>

CSS

body{
  height: 1220px;
}

svg{
   position: absolute;
   top: 1200px;
}
.line-delay.start {
  stroke-dasharray: 200;
  animation: draw-svg 3s linear normal;

}

@keyframes draw-svg {
  from {
    stroke-dashoffset: 200;
  }
  to {
    stroke-dashoffset:0;
    
  }
}

JavaScript

function isElementInViewport(elem) {
    var $elem = $(elem);

    // Get the scroll position of the page.
    var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
    var viewportTop = $(scrollElem).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

    // Get the position of the element on the page.
    var elemTop = Math.round( $elem.offset().top );
    var elemBottom = elemTop + $elem.height();

    return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
}

// Check if it's time to start the animation.
function checkAnimation() { 
    var $elem = $('svg .line-delay');
		
    // If the animation has already been started
    if ($elem.hasClass('start')) return;

    if (isElementInViewport($elem)) { 
        // Start the animation
        //$elem.addClass('start'); 
        $elem.attr("class", "line-delay start");
    }
}

// Capture scroll events
$(window).scroll(function(){
 
   checkAnimation();
});