Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-browser method for detecting the scrollTop of the browser window

People also ask

What is window scrollTop?

An element's scrollTop value is a measurement of the distance from the element's top to its topmost visible content. When an element's content does not generate a vertical scrollbar, then its scrollTop value is 0 .

Is scrollTop deprecated?

scrollTop is deprecated in strict mode.


function getScrollTop(){
    if(typeof pageYOffset!= 'undefined'){
        //most browsers except IE before #9
        return pageYOffset;
    }
    else{
        var B= document.body; //IE 'quirks'
        var D= document.documentElement; //IE with doctype
        D= (D.clientHeight)? D: B;
        return D.scrollTop;
    }
}

alert(getScrollTop())

Or just simple as:

var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;

If you don't want to include a whole JavaScript library, you can often extract the bits you want from one.

For example, this is essentially how jQuery implements a cross-browser scroll(Top|Left):

function getScroll(method, element) {
  // The passed in `method` value should be 'Top' or 'Left'
  method = 'scroll' + method;
  return (element == window || element == document) ? (
    self[(method == 'scrollTop') ? 'pageYOffset' : 'pageXOffset'] ||
    (browserSupportsBoxModel && document.documentElement[method]) ||
    document.body[method]
  ) : element[method];
}
getScroll('Top', element);
getScroll('Left', element);

Note: you'll notice that the above code contains a browserSupportsBoxModel variable which is undefined. jQuery defines this by temporarily adding a div to the page and then measuring some attributes in order to determine whether the browser correctly implements the box model. As you can imagine this flag checks for IE. Specifically, it checks for IE 6 or 7 in quirks mode. Since the detection is rather complex, I've left it as an exercise for you ;-), assuming you have already used browser feature detection elsewhere in your code.

Edit: If you haven't guessed already, I strongly suggest you use a library for these sorts of things. The overhead is a small price to pay for robust and future-proof code and anyone would be much more productive with a cross-browser framework to build upon. (As opposed to spending countless hours banging your head against IE).


I've been using window.scrollY || document.documentElement.scrollTop.

window.scrollY covers all browsers except IEs.
document.documentElement.scrollTop covers IE.