getting the browser's scroll position with javascript
May
09
1
0
Sometimes you need to dynamically detect the browser's scroll position. Dealing with browser inconsistencies is a PITA, but here is a javascript function that I use that gets the job done.
function getScrollXY() {
var x = 0, y = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
// Netscape
x = window.pageXOffset;
y = window.pageYOffset;
} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
// DOM
x = document.body.scrollLeft;
y = document.body.scrollTop;
} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
// IE6 standards compliant mode
x = document.documentElement.scrollLeft;
y = document.documentElement.scrollTop;
}
return [x, y];
}You can then call it like so:
var xy = getScrollXY(); var x = xy[0]; var y = xy[1];
