title: Jquery follow scroll
body: <p>I have a sort of sidebar on my website, which has to scroll down together with the user so that it is always in the view. </p>
  
  <p>The code I'm using now is actually working fine however there is one problem. On smaller screens the sidebar scrolls before your at the sidebar thus making it impossible to see it all even if you scroll.</p>
  
  <p>So what I want is the sidebar to scroll with the bottom instead of it being pushed down with the top so that when you reach the end of the sidebar it starts to scroll.</p>
  
  <p>This is the code that I'm currently using.</p>
  
  <p><code></p>
  
  <pre><code>var documentHeight = 0;
  var topPadding = 10;
  $(function() {
      var offset = $("#mainright").offset();
      documentHeight = $(document).height();
      $(window).scroll(function() {
          var sideBarHeight = $("#mainright").height();
          if ($(window).scrollTop() &gt; offset.top) {
              var newPosition = ($(window).scrollTop() - offset.top) + topPadding;
              var maxPosition = documentHeight - (sideBarHeight);
              if (newPosition &gt; maxPosition) {
                  newPosition = maxPosition;
              }
              $("#mainright").stop().animate({
                  marginTop: newPosition
              });
          } else {
              $("#mainright").stop().animate({
                  marginTop: 0
              });
          };
      });
  });
  </code></pre>
  
  <p></code></p>