I want to get it so the last div on my sidebar stays sticky when the page scrolls, but stops at the footer. I have it almost working with an online tutorial, but the calculation messes up when disqus comments load and it only goes to a certain point.
Here's a working version http://jsfiddle.net/k56yR/1/, but Is there an easy way to do something like calculate the footer height and then tell it to stop scrolling that far from the bottom of the page?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With