9

I am working on a scrolling page design and I have the following Javascript to hide and show a dialog box:

        if(window.pageYOffset >= 300){

            $('#m1').fadeIn('slow');

    }

    if(document.documentElement.scrollTop >=300){

        $('#m1').fadeIn('slow');

    }

This works great in Chrome,FF, IE9+

However, in IE8,7 it only kind of works. It shows and hides the element properly but the delay between when it evaluates the scroll position and when it hides the element is horrendous. Also, there is no fade, it just happens.

I am wondering if its just a problem with IE8 that I need to deal with or if there is a way for me to achieve a reactive, clean fade with IE8.

Shawn Borsky
  • 95
  • 1
  • 1
  • 7
  • The title of this question is looking for a "jQuery Alternative" but the part that's incompatible with IE8 (`pageYOffset`) has nothing to do with jQuery. – Sparky Apr 23 '12 at 19:00
  • Fixed. When I posted it, it seemed like a jQuery issue. – Shawn Borsky Apr 23 '12 at 20:27

2 Answers2

26

pageYOffset and pageXOffset are not supported in IE8 and before, try this function:

// Return the current scrollbar offsets as the x and y properties of an object
function getScrollOffsets() {

    // This works for all browsers except IE versions 8 and before
    if ( window.pageXOffset != null ) 
       return {
           x: window.pageXOffset, 
           y: window.pageYOffset
       };

    // For browsers in Standards mode
    var doc = window.document;
    if ( document.compatMode === "CSS1Compat" ) {
        return {
            x: doc.documentElement.scrollLeft, 
            y: doc.documentElement.scrollTop
        };
    }

    // For browsers in Quirks mode
    return { 
        x: doc.body.scrollLeft, 
        y: doc.body.scrollTop 
    }; 
}
Ram
  • 143,282
  • 16
  • 168
  • 197
  • document.documentElement.scrollTop works fine to detect the position in IE8. Are you saying the Jquery fade problem is a result of the browser being unable to detect the scroll offset properly? – Shawn Borsky Apr 23 '12 at 18:36
  • That seems unlikely, since it obviously does detect it...It just behaves differently than it should. – Isaac Fife Apr 23 '12 at 18:40
  • A combination of this code and setting opacity to inherit fixed it. Thanks @Raminson. – Shawn Borsky Apr 23 '12 at 20:32
  • Here is a nice article to go along with this answer https://developer.mozilla.org/en-US/docs/Web/API/window.scrollY?redirectlocale=en-US&redirectslug=DOM/window.scrollY – marty Sep 11 '13 at 13:26
  • `doc.documentElement.scrollTop` not `ddc.documentElement.scrollTop` :) – unbreak Mar 12 '14 at 09:34
2

You can also fix it using this:

document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset;

So you have it

if((document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset) >= 300){
        $('#m1').fadeIn('slow');
}

In this way you can avoid replicate code.

pm.calabrese
  • 386
  • 6
  • 10