Search code examples
jqueryhtmlcsssticky

Stick Fixed Sidebar stop before footer


Well, I tried some js but I didn't got how to do it. I want to make a Stick Sidebar but I want to the 'fixed' move stop before #footer.

I try it:

jQuery("document").ready(function($){

var nav = $('#ultimos-videos');

$(window).scroll(function () {
    if ($(this).scrollTop() > 420) {
        nav.addClass("ultimos-videos-fixed");
    } else {
        nav.removeClass("ultimos-videos-fixed");
    }
}); });

And my divs like this:

#ultimos-videos {}
.ultimos-videos-fixed {position: fixed; top: 70px;}

Anybody has a solution? Thank's!


Solution

  • So you just need to calculate the distance from the footers top position minus the sidebars height and any other height that you have and by the looks of things by your fixed css that you have posted there is another 70 px and then fire another class like you did with the ultimos-videos-fixed class. The only difference is you will be positioning the element absolutetly at the bottom of whatever content your sidebar is in so you will need to place your sidebar in a relative positioned element so it will be able to stop. So all that being said here is how you would go about doing this:

    Check the following JSFiddle of the whole thing in action. I have put some comments in the javascript section for you to read so you can better understand how it all works Click Here To View Fiddle

    jQuery("document").ready(function($){
      var nav = $('#ultimos-videos');
      var footerTop = $('footer').offset().top;
      var navHeight = $('#ultimos-videos').outerHeight();
      var stopPoint = footerTop - navHeight - 70;
      $(window).scroll(function () {
          if ($(this).scrollTop() >= 420) {
              nav.addClass("ultimos-videos-fixed");
          } else {
              nav.removeClass("ultimos-videos-fixed");
          }
          if ($(this).scrollTop() >= stopPoint) {
              nav.addClass("ultimos-videos-stop");
          } else {
              nav.removeClass("ultimos-videos-stop");
          }
      });
    });
    

    css:

    .whatever-div-your-sidebar-is-a-child-of {
      posiiton:relative;
    }
    .ultimos-videos-fixed {
      position: fixed; 
      top: 70px;
      left: 0;
    }
    .ultimos-videos-stop{
      position:absolute;
      bottom: 0;
      top:auto;
      left: 0;
    }