Ilja
Ilja

Reputation: 46479

jQuery not working in firefox and internet explorer

Alright, I have jQUery function which adds class to a div#float once div#floatLunch gets to the top of the page. It works fine in chrome, but doesn't work at all in mozila and IE. Here is a fiddle: http://jsfiddle.net/JKA7j/1/

Code

<script type="text/javascript">
$(window).scroll(function() {
    var targetDiv = $('#float');
    var matchHeight = $('#floatLunch').position().top;
    if ($(document.body).scrollTop() >= matchHeight) {
        // this is where you're css amendments would be done
        if (!targetDiv.hasClass('fixedPos')) {
            targetDiv.addClass('fixedPos');
        }
    } else {
        if (targetDiv.hasClass('fixedPos')) {
            targetDiv.removeClass('fixedPos');
        }
    }
});
</script>

Is there a fix to this problem?

Upvotes: 2

Views: 1473

Answers (3)

Jasper
Jasper

Reputation: 76003

Change out: $(document.body) for $(this) which is the same as $(window).

Here is a demo: http://jsfiddle.net/JKA7j/7/ (tested to work with Chrome 15, IE 8, Firefox 8, Opera 11).

Upvotes: 3

Andrey Nikishaev
Andrey Nikishaev

Reputation: 3882

Here is working code: http://jsfiddle.net/JKA7j/4/

$(window).scroll(function() {
    var targetDiv = $('#float');
    var matchHeight = $('#floatLunch').offset().top;
    if ($(window).scrollTop() >= matchHeight) {
        // this is where you're css amendments would be done
        if (!targetDiv.hasClass('fixedPos')) {
            targetDiv.addClass('fixedPos');
        }
    } else {
        if (targetDiv.hasClass('fixedPos')) {
            targetDiv.removeClass('fixedPos');
        }
    }
});

Upvotes: 1

David Hellsing
David Hellsing

Reputation: 108500

Change this:

$(document.body).scrollTop()

to:

$(document).scrollTop()

Also, you can move the matchHeight and targetDiv declarations and place them outside the scroll event, no need to put extra load on the script just to find the same result every time:

var targetDiv = $('#float'),
    matchHeight = $('#floatLunch').position().top;

$(window).scroll(function() {
    targetDiv.toggleClass('fixedPos', $(document).scrollTop() >= matchHeight);
});

http://jsfiddle.net/JKA7j/3/

Upvotes: 3

Related Questions