Search code examples
javascriptjqueryhtmlonscroll

How to stop follow sidebar when it reach to footer?


I have sidebar that following by scrolling. If the sidebar reach down to footer, how to stop to follow?

This is what I tried so far here.

$(function() {
  var floatPosition = parseInt($("#left_menu").css('top'));

  $(window).scroll(function() {
    var scrollTop = $(window).scrollTop();
    var newPosition = scrollTop + floatPosition + "px";
    var newPosition2 = scrollTop;

    $("#left_menu").stop().animate({
      "top" : newPosition2
    }, 400);

  }).scroll();
});        
.left_menu{position:absolute;top:0;left:0;width:100px; height:330px; margin-top: 30px; background:green}
#footer { background:gray; height:100px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<div id="left_menu" class="left_menu">menu</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div id="footer">foot</div>

Please help


Solution

  • You should check if bottom position of #left_menu is greater than top position of #footer, prevent increasing it. Note that you should remove CSS margin-top of #left_menu

    $(window).scroll(function() {
      var scrollTop = $(window).scrollTop();
      var height = $("#left_menu").height();
      var top = $("#footer").offset().top;
    
      if (scrollTop+height > top)
        scrollTop = top-height;
    
      $("#left_menu").stop().animate({
        "top": scrollTop
      }, 400);
    }).scroll();
    

    $(window).scroll(function() {
      var scrollTop = $(window).scrollTop();
      var height = $("#left_menu").height();
      var top = $("#footer").offset().top;
        
      if (scrollTop+height > top)
        scrollTop = top-height;
      
      $("#left_menu").stop().animate({
        "top": scrollTop
      }, 400);
    }).scroll();
    .left_menu{
      position:absolute;
      top:0;
      left:0;
      width:100px; 
      height:330px; 
      background:green
    }
    #footer { 
      background:gray; 
      height:100px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="left_menu" class="left_menu">menu</div>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    <div id="footer">foot</div>
    <br><br><br><br><br><br><br><br>