Reputation: 46479
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
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
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
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);
});
Upvotes: 3