I think your problem is that your $('#footer').offset().top
value changes after your disqus comments load. So you need to update footerTop
(and limit
based on the new footerTop
value) after your comments load or every time your event fires.
something like:
$(function(){ // document ready
if ($('#sticky').length) { // make sure "#sticky" element exists
var el = $('#sticky');
var stickyTop = $('#sticky').offset().top; // returns number
var stickyHeight = $('#sticky').height();
$(window).scroll(function(){ // scroll event
var limit = $('#footer').offset().top - stickyHeight - 20;
var windowTop = $(window).scrollTop(); // returns number
if (stickyTop < windowTop){
el.css({ position: 'fixed', top: 0 });
}
else {
el.css('position','static');
}
if (limit < windowTop) {
var diff = limit - windowTop;
el.css({top: diff});
}
});
}
});
As with most of the cases, there is a jQuery plugin for this, as julianm pointed out in his comment, available here. It also supports a stopper value, to stop the sticky box at any desired position.