Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop floating sticky sidebar div at footer (almost working)

Tags:

jquery

sticky

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?

like image 983
Mike Jonas Avatar asked May 19 '12 22:05

Mike Jonas


1 Answers

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.

like image 185
19greg96 Avatar answered Oct 11 '22 13:10

19greg96