title: Move div with window scroll not consistent
body: <p>I need my sidebar to scroll up and down with the window but stop when the div is at its top or bottom. The code below works when the page is first loaded and scrolled down or when the page is scrolled up slowly, but when the page is scrolled to the very bottom of the sidebar div, the page has to reach the top (and then some) in order to trigger that margin change. </p>
  
  <p>Is there some other trigger I should be looking for besides just on scroll? How can I adjust this code to properly adjust the div?</p>
  
  <pre><code>$(window).on("load scroll", function() {
      var scrollYpos = $(document).scrollTop();
      var sidebarinfo = $("#sidebar").offset().top + $("#sidebar").height();
      var windowinfo = $(window).height() + $(window).scrollTop();
      if ((windowinfo)&lt;(sidebarinfo)){
          $('#sidebar').css('margin-top', -scrollYpos);
      }
  });
  </code></pre>
  
  <p>The sidebar div is fixed position. If I use absolute position, the div scrolls fine, but it doesn't stop when the bottom of the div has been reached - it just continues to scroll with the window.</p>
  
  <hr>
  
  <p>I've fixed the main part of the problem with this code.</p>
  
  <pre><code>$(window).on("load scroll", function() {
      var sidebarinfo = $("#sidebar").scrollTop() + $("#sidebar").height();
      var windowinfo = $(window).innerHeight() + $(window).scrollTop();
      if ((windowinfo)&lt;(sidebarinfo)){
          $('#sidebar').css('top', -($(window).scrollTop()));
      }
  });
  </code></pre>
  
  <p>The only problem is on page load, the sidebar gets stuck in the wrong position until it is scrolled all the way up (and more).</p>