Search code examples
javascriptjqueryhtmlcsssidebar

Stop sidebar on end div


Goodmorning,

Ive a information page with a sidebar on the right site of the page that follows the screen when scrolling but when he reach the and of the div its still following the page as.

 var $sidebar = $("#sidebar"),
   $window = $(window),
   offset = $sidebar.offset(),
   topPadding = 230;

 $window.scroll(function() {
   if ($window.scrollTop() > offset.top) {
     $sidebar.stop().animate({
       marginTop: $window.scrollTop() - offset.top + topPadding
     });
   } else {
     $sidebar.stop().animate({
       marginTop: 15,
       marginBottom: 200
     });
   }
 });
#sidebar {
  width: 190px;
}
#sidebar li {
  border-left: 1px solid orange;
  border-bottom: 1px solid orange;
  border-top: 1px solid orange;
  list-style-type: none;
  text-align: left;
  padding-left: 8px;
  border-collapse: collapse;
}
#sidebar li:hover {
  font-size: 17px;
  font-weight: bold;
  background-color: #FF8D00;
  color: white;
}
#sidebar lu {
  list-style-type: none;
  text-decoration: none;
}
#sidebar li:hover a {
  color: white;
}
body {
  height: 3000px;
}
<div id="sidebar" class="span3 over_inhoud rechts Padding-top-orange">
  <ul>
    <li><a href="#Agenda">Agenda</a>
    </li>
    <li><a href="#urenregistratie">Urenregistratie</a>
    </li>
    <li><a href="#rapportage">Rapportage</a>
    </li>
    <li><a href="#Factureren">Factureren</a>
    </li>
    <li><a href="#Koppelingen">Koppelingen</a>
    </li>
    <li><a href="#planning">Planning</a>
    </li>
    <li><a href="#Boekhouden">Boekhouden</a>
    </li>
    <li><a href="#Mobile">Mobile App</a>
    </li>
    <li><a href="#Ontwikkeling">Ontwikkeling</a>
    </li>
  </ul>
</div>

http://www.clockwise.mar-bakker.nl/info.html


Solution

  • You can use height of the div to get if you are reached at the bottom of the div or not and animate it in "else if".

    You can get height of the div using

    div_height = $("#InformatieDiv").height()
    

    So there will be three branches as follows:

    if ($window.scrollTop() > offset.top){
      #CODE TO STOP SCROLLING UP
    }else if($window.scrollTop() < (offset.top + div_height)){
      #CODE TO STOP SCROLLING DOWN
    }else{
    }
    

    I hope this will help you.