29

Is it possible to change the scrollbar position when the user reaches a certain point scrolling down a web page? For example once you reached half way down down the page the scrollbar would move automatically back to the top.

Flip
  • 6,233
  • 7
  • 46
  • 75
alan
  • 391
  • 1
  • 4
  • 8

4 Answers4

40

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.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
12

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.

Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239
thedayturns
  • 9,723
  • 5
  • 33
  • 41
4

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.

Eric Wendelin
  • 43,147
  • 9
  • 68
  • 92
2

(window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop) ought to give you the current scroll position in just about any browser.

David
  • 2,164
  • 13
  • 11