views:

87

answers:

3

I'm trying to detect the position of the browser scrollbar with Javascript to decide where abouts in the page the current view is. My guess is that I'd have to detect where the thumb on the track is, and then the height of the thumb as a percentage of the total height of the track. Am I over-complicating it, or does Javascript offer an easier solution than that? Any ideas code-wise. Thanks.

A: 

You can use element.scrollTop and element.scrollLeft to get the vertical and horizontal offset, respectively, that has been scrolled. element can be document.body if you care about the whole page. You can compare it to element.offsetHeight and element.offsetWidth (again, element may be the body) if you need percentages.

Max Shawabkeh
What browser are you using? Getting the body is done differently in different browsers (`element` and `document.body` were just examples). See http://www.howtocreate.co.uk/tutorials/javascript/browserwindow for details.
Max Shawabkeh
I got it to give me the correct value on Firefox 3.6 with `window.pageYOffset`, but can't get anything working on IE7. Tried `window.pageYOffset`, `document.body.scrollTop`, `document.documentElement.scrollTop`, `element.scrollTop`
Paul
A: 

this site has a function at the bottom that looks pretty thorough.

http://www.howtocreate.co.uk/tutorials/javascript/browserwindow

i found another page quite awhile ago with a handy chart of which properties work in which browsers but i can't find it at the moment.

lincolnk
A: 
document.getScroll= function(){
 if(window.pageYOffset!= undefined){
  return [pageXOffset, pageYOffset];
 }
 else{
  var sx, sy, d= document, r= d.documentElement, b= d.body;
  sx= r.scrollLeft || b.scrollLeft || 0;
  sy= r.scrollTop || b.scrollTop || 0;
  return [sx, sy];
 }
}
kennebec