From top-fixed to bottom-fixed when reaching the footer

From top-fixed to bottom-fixed when reaching the footer

I need to stop a fixed sidebar when the footer is reached. I have the code below, but if you scroll down, the sidebar gets over the footer when reaching it. Of course, it will be fixed to the top again when scrolling up. Any help? jsFiddle

  1. $(window).scroll(function() { if($(window).scrollTop() + $(window).height() > $(document).height() - 210) { alert ("footer reached!"); $('.sidebar').css({ position: 'fixed', bottom: 210, }) } else { $('.sidebar').css({ position: 'fixed', top: 0 }) } });
  1. .body { overflow: hidden; height: 1000px; } .sidebar { height: 400px; width: 200px; background: red; float: left; } .footer { height: 200px; background: blue; }
  1. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div class="body"> <div class="sidebar"></div> </div> <div class="footer"></div>