I use the following piece of code to make a div’s position fixed when scrolled down (so it will stay in the window). It works perfectly fine, but in IE7 I get the error: offset().top is null or not an object.
$(document).ready(function(){
var msie6 = $.browser == 'msie' && $.browser.version < 7;
if (!msie6) {
var top = $('#comment').offset().top - parseFloat($('#comment').css('margin-top').replace(/auto/, 0));
$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();
// whether that's below the form
if (y >= top) {
// if so, ad the fixed class
$('#comment').addClass('fixed');
} else {
// otherwise remove it
$('#comment').removeClass('fixed');
}
});
}
});
Googling I found this (see bottom post by Earl Jenkins) http://api.jquery.com/offset/
In which he solves this particular error. But, jQuery & javascript beginner as I am, I don’t know how to implement this fix, because in his post he uses a fixed value (100), and in the piece of code above it doesn’t.
I tried to fix by doing this:
var fix = $('#comment').offset();
var top = fix.top - parseFloat($('#comment').css('margin-top').replace(/auto/, 0));
But it doesn’t do the trick. Thanks for your help!
I think that the problem you were running into was that you were accessing the
topproperty of thewindowobject when your#commentDIV wasn’t present.This problem isn’t well documented, but I’ve run into it before. I found a vague explanation of the cause at Dottoro.com’s reference to the window object.
The gist of it is that if you had changed your variable name from top to something else, the problem would’ve gone away.