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

Hot Pastrami picture Hot Pastrami · May 16, 2009 · Viewed 63.6k times · Source

What is the best cross-browser way to detect the scrollTop of the browser window? I prefer not to use any pre-built code libraries because this is a very simple script, and I don't need all of that deadweight.

Answer

kennebec picture kennebec · May 16, 2009
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())