JSFiddle - React, Tailwind, and code Playground

by amullins

HTML

<div class="full" id="one">
   <span style="width:100%; background-color:blue">
   <a href="#two" >Scroll to 2</a>
   </span>    
</div>


<div class="full" id="two">
    <span style="width:100%; background-color:blue">
    <a href="#one" >Scroll to 1</a></span>
</div>

CSS

html,body { 
    width:100%;
    height:100%;}

.full {
    height:100%;
    width:100%;}

#one {background-color:green}
#two {background-color:red}

JavaScript

window.addEventListener("load", function() {
var anchors = document.getElementsByTagName("a"), animationInterval, stopInterval, activeAnchor;
  var frameTime = 17;
  var totalTime = 1000;
  var scrollTarget = null;
    function animateScroll() {
        
        if(scrollTarget === null)
            scrollTarget = document.getElementById(activeAnchor.getAttribute("href").split("#")[1]);
        console.log("Animating: targetY = " + scrollTarget.offsetTop +", sourceY = " + activeAnchor.offsetTop);
        window.scrollBy(0,(scrollTarget.offsetTop - activeAnchor.offsetTop)*frameTime/totalTime);
        if(window.scrollY === scrollTarget.offsetTop)
        {
            clearInterval(animationInterval);
            scrollTarget = null;
        }
    }
    
  for(var i = 0; i < anchors.length; i++)
  {
    anchors[i].removeEventListener("click");
    anchors[i].addEventListener("click", function(e) {
        e.preventDefault();
        activeAnchor = this;
        animationInterval = setInterval(animateScroll, frameTime);
        return false;
    });
  }
});