Smooth Scroll to top with Simple JS

HTML
<div class="body">Scroll down</div> <div class="elStop">Go to top</div>
CSS
.body{ height:1000px; text-align:center; } .elStop{ display:block; width:100%; text-align:center; cursor:pointer; background-color:#444; color:#eee; padding:10px; box-sizing:border-box; }
JAVASCRIPT
var cpo=0,c,cpcount=1,sctop=document.getElementsByClassName("elStop"); var db,dn; for (var i = sctop.length - 1; i >= 0; i--) { sctop[i].onclick = toTop; } window.onscroll = function(){ cpo = window.pageYOffset; //alert(cpo); if ( cpo === 0 ) { clearInterval(c); cpcount = 1; } } function toTop(){ if( cpo % 2 === 0 ){ if( cpo > 10000 && cpo < 100000 ){ addval = 40; }else if( cpo > 100000 ){ addval = 1000; }else{ addval = 2; } }else{ if( cpo > 10000 && cpo < 100000 ){ addval = 39; }else if( cpo > 100000 ){ addval = 999; }else{ addval = 1; } } //console.log("Pagey "+cpo); //console.log("count "+cpcount); //console.log("Pagey("+cpo+") - count("+cpcount+")"); if ( cpo !== 0 || cpo > 0 ) { cpo = (cpo > 0) ? cpo-cpcount : cpo-cpo; window.scrollTo(0,cpo); cpcount += addval; a(); } //console.log(window.pageYOffset); } function a(){ clearInterval(c); c = setInterval(toTop,20); }
Expand for more options Login