Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE8 alternative to window.scrollY?

I'm trying to determine how many pixels down I've scrolled using window.scrollY. But this isn't supported in IE8. What is the safe, cross-browser alternative?

like image 364
Jake Wilson Avatar asked May 17 '13 22:05

Jake Wilson


4 Answers

The cross-browser compatible version for window.scrollY is document.documentElement.scrollTop. Please see the 'Notes' section of this piece of Mozilla documentation for a full, detailed workaround in IE8 and before.

As mentioned here, pageYOffset is another alternative to window.scrollY (note though that this is only IE9+ compatible).

In regard to the link above, check Example 4 for a fully compatible way to get the scroll position (it even accounts for zoom as @adeneo mentioned!) using document.documentElement.scrollTop and document.documentElement.scrollLeft.

Here, try out the example for yourself!

like image 168
dsgriffin Avatar answered Oct 22 '22 18:10

dsgriffin


If you don't have to use it a lot, just do:

var scroll = window.scrollY //Modern Way (Chrome, Firefox) 
|| document.documentElement.scrollTop (Old IE, 6,7,8)
like image 41
Tom Sarduy Avatar answered Oct 22 '22 19:10

Tom Sarduy


If you're using jQuery, I used $(window).scrollTop() to get the Y position in IE 8. It seemed to work.

like image 5
Daniel Avatar answered Oct 22 '22 17:10

Daniel


If you have a valid reason for not just using a library to handle this kind of base functionality, don't hesitate 'not to re-invent the wheel'.

Mootools is open source, and you can just 'steal' its implementation, relevant snippets:

getScroll: function(){
    var win = this.getWindow(), doc = getCompatElement(this);
    return {x: win.pageXOffset || doc.scrollLeft, y: win.pageYOffset || doc.scrollTop};
}

function getCompatElement(element){
    var doc = element.getDocument();
    return (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body;
}

These 2 are the core of deciding which compatibility mode your current browser it has, and then whether to use window.pageYOffset or document.body.scrollTop based on that or even document.html.scrollTop for really ancient buggy browsers.

like image 3
Niels Keurentjes Avatar answered Oct 22 '22 18:10

Niels Keurentjes