Mike Jonas Mike Jonas - 2 months ago 14x
jQuery Question

Stop floating sticky sidebar div at footer (almost working)

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 {

          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.