0

i have written this which works fine. It jumps up to the top, but I would like it to be a smooth scroll. How can i achieve that without JQuery?

document.querySelector('.scrolltop').addEventListener('click', footerScroll)

function footerScroll(){
   console.log("clicked");
   window.scrollTo(0, 0);
};

Thanks.

1 Answers1

0

try this:

        (function(){
        var color= 'red';
        var fhwScrollerDiv = document.createElement('div');
        fhwScrollerDiv.innerHTML='<svg width="50" height="50" viewbox="0 0 100 100"><circle  fill="'+color+'" cx="50" cy="50" r="50" /><path stroke="white" stroke-width="16" stroke-linecap="round" d="M50 80 L50 20 M50 20 L80 50 M50 20 L20 50"/></svg>';
        fhwScrollerDiv.style.cssText='z-index:1000;position:fixed;bottom:10px;right:10px;cursor:pointer;display:none;transition:all 0.5s;';
        document.body.appendChild(fhwScrollerDiv);
        var _=fhwScrollerDiv.style;
        window.onscroll = function() {
            if (this.pageYOffset > 200) {
                _.opacity = "0.5";
                _.display = "block";
            } else {
                _.opacity = "0";
                _.display = "none";
            }
        };
        fhwScrollerDiv.onmouseover = function() {
          _.opacity = "1";
        };
        fhwScrollerDiv.onmouseout = function() {
          _.opacity = "0.5";
        };
        var scrollen = function(){
            var scrollDuration = 500,
            scrollHeight = window.pageYOffset,
            scrollStep =  scrollDuration / 15 , 
            scrollCount = 0,
            scrollInterval = setInterval( function() {
                if ( window.pageYOffset != 0 ) {
                    scrollCount = scrollCount + 1;  
                    window.scrollTo( 0, ( scrollHeight-scrollCount*scrollStep) );
                } 
                else clearInterval(scrollInterval); 
                },15 );

        }
        fhwScrollerDiv.onclick = scrollen;  
        fhwScrollerDiv.addEventListener('touchstart', function(){
            event.preventDefault();
            scrollen();
        });
        })();

js fiddle

Frank Wisniewski
  • 1,182
  • 8
  • 7