-1

I would like to scroll up to the top smoothly with pure JS, with code not much longer than the current one. Now, it just scrolls up 1px (I think it's px)

Code snippet:

    var textdiv = document.getElementById('infoblok');
    var currentscroll = textdiv.scrollTop;
    for(i = currentscroll; i>0; i--){
      textdiv.scrollTop = currentscroll-1;
   }
  • 3
    Possible duplicate of [Cross browser JavaScript (not jQuery...) scroll to top animation](http://stackoverflow.com/questions/8917921/cross-browser-javascript-not-jquery-scroll-to-top-animation) – TyBourque Oct 17 '16 at 19:17

2 Answers2

1

There are libraries that are best suited for this task.

However, you can try this, but remember (1) the user may interact while you are scrolling which will produce undesired user experience, (2) you should do this async so that the page does not freeze.

var textdiv = document.getElementById('infoblok');
var currentscroll = textdiv.scrollTop;
var interval = setInterval(function()
{
    if( textdiv.scrollTop <= 0 ) clearInterval(interval);
    textdiv.scrollTop -= 1;
}, 10);

This example will scroll up 1px at a time every 10ms. You can play with the 1 and 10 for different scroll speed.

Simon
  • 2,353
  • 1
  • 13
  • 28
0

This may help. I just did a quick google search.

https://coderwall.com/p/hujlhg/smooth-scrolling-without-jquery

Mark Handy
  • 1,180
  • 1
  • 11
  • 23