Max Frai
Max Frai

Reputation: 64266

Scroll page until some height

how can I scroll the page with javascript until the scrolled height will be some predefined number of pixels?

function pageScroll() {
    // Next line is pseudocode:
    if (window.ScrolledHeight != SOME_NUM)
       window.scrollBy(0,50);
}
scrolldelay = setTimeout('pageScroll()',100);

There should be some logical checking of something. Could you help me, how to get scrolled height?

Upvotes: 0

Views: 1905

Answers (3)

qw3n
qw3n

Reputation: 6334

First off you shouldn't be using setTimeout you should be using setInterval. Basically because it fulfills your purpose better and it is more accurate as far as actually time. Google it if you want more info on that topic. But what you need is the clearInterval method. Also it is faster to use anonymous functions inside of setTimeout and setInterval.

startPageScroll(){
  var scrollAmt = 0;
  var id=setInterval(function(){
    if(scrollAmt</*Whatever your limit is*/){
      window.scrollBy(0,50);
      scollAmt+=50;
    }
    else{clearInterval(id);}
  },100);
}

There are ways of getting the actual scroll of the page, but you would have to do something like this which is quite a bit more code then just keeping a running total of how far you have moved.

var scroll;

if(window.pageYOffset){
  scroll=window.pageYOffset;
}
else{
  scroll=document.body.scrollTop;
}

Here is a link that might help http://codepunk.hardwar.org.uk/ajs02.htm.

Upvotes: 0

R. Hill
R. Hill

Reputation: 3620

You already had valid answers, but I will add a bit of flavor, it scrolls but slows down before reaching the targeted scroll point:

function pageScroll() {
    var delta = min(SOME_NUM-window.ScrolledHeight)>>1,50);
    if (delta > 0) {
       window.scrollBy(0,delta);
       setTimeout('pageScroll()',100);
    }
}

A nice side effect is that it should reach exactly SOME_NUM regardless it is a multiple of 50 (your scroll amount) or not.

Upvotes: 0

David Burhans
David Burhans

Reputation: 363

Could you use a variable outside of the function that would increment the value by 50 pixels everytime pageScroll ran and then check to see if that is equal to or greater than the value you are looking for?

e.g.

var scrollAmount = 0;

function pageScroll() {
    window.scrollBy(0,50);
    scrollAmount += 50;
    if(scrollAmount < 200) {
        scrolldelay = setTimeout('pageScroll()',100);
    }
}

You could also make the function take in a parameter that you modify if you don't want to use the global variable.

Upvotes: 1

Related Questions