0

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/

6
  • 1
    The problem is more likely to be with .scrollTop() than with .toggleClass().
    – Pointy
    Commented Sep 17, 2013 at 17:22
  • 2
    why are you mixing $ and jQuery and what error do you get?
    – j08691
    Commented Sep 17, 2013 at 17:23
  • No errors, simply it doesn't change color.
    – Elena
    Commented Sep 17, 2013 at 17:26
  • Have you checked to see if the "scroll" event fires at all?
    – Pointy
    Commented Sep 17, 2013 at 17:26
  • 1
    @j08691 what do you mean with mixing $ and jQuery. I only see that all jQuery result sets are prefixed with a $ which is not an uncommon practice to show directly in source that it is a jQuery result set.
    – t.niese
    Commented Sep 17, 2013 at 17:35

1 Answer 1

2

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

1
  • 2
    Thank you, you resolved! I didn't know of this problem with $document on IE, I thought it was a toggleClass problem because I found several questions on this on the net and I had focused on this. You never stop learning, thank you!
    – Elena
    Commented Sep 18, 2013 at 7:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.