Question

I'm trying to change color to a header when it reaches a certain scroll. I use this script with jQuery:

var $document = jQuery(document),
    $element = jQuery('#header'),
    className = 'red';

$document.scroll(function() {
    $element.toggleClass(className, $document.scrollTop() >= 400);
}); 

That works on every browser, except for IE8. Does IE8 does not support the toggleClass? How can I solve it?

Any help would be appreciated. Thanks

jsFiddle: http://jsfiddle.net/itzuki87/e4XTw/
in IE: http://jsfiddle.net/itzuki87/e4XTw/show/

Was it helpful?

Solution

The problem is $(document) is read different in IE. IE prefers you to use $(window). You'll find the following to be much more cross-browser compatible.

$(function() {
    $(window).scroll(function(e) {
        $("#header").toggleClass("red", $(this).scrollTop() >= 400);
    });
})

Or using your variable type setup:

jQuery(function() {
    var $window = jQuery(window),
        $element = jQuery("#header"),
        className = "red";

    $window.scroll(function(e) {
        $element.toggleClass(className, jQuery(this).scrollTop() >= 400);
    });
})

See working in IE8! and more (Safari, FF, Chrome, Opera)!


Using my smaller HTML

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top