views:

53

answers:

3

Hello, 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?

A: 

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.

David Burhans
Nice idea. I'll wait a few time, maybe there is property which indicates the correct height otherwise I'll mark your post as answer.
Ockonal
A: 

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.

qw3n
setTimeout is just for sample. The code will be ran in the cycle.
Ockonal
A: 

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.

R. Hill