How to change scrollbar position? How to change scrollbar position? javascript javascript

How to change scrollbar position?


You can calculate the percentage of the current position of the scrollbar using the onscroll event, and if it reaches the 50 % the scroll position can be set to the top of the page with the scrollTo function:

window.onload = function () {   window.onscroll = function () {     var doc = document.body,     scrollPosition = doc.scrollTop,    pageSize = (doc.scrollHeight - doc.clientHeight),    percentageScrolled = Math.floor((scrollPosition / pageSize) * 100);      if (percentageScrolled >= 50){ // if the percentage is >= 50, scroll to top       window.scrollTo(0,0);      }    }; };

You can check my example here.


Yup, I've seen it a few times. Here is some JS code:

window.scrollBy(0,50)

50 is the amount of pixels you want to scroll by.


The three scrolling functions you'll want to concern yourself with are window.scroll(x,y), window.scrollBy(dx,dy), and window.scrollTo(x,y).

As David mentioned you'll need the scroll position to know where you are and use the window.onscroll event to fire off this calculation.