title: Stopping sticky sidebar at footer
body: <p>I want to get it so the last div on my sidebar stays sticky when the page scrolls, but stops at the footer. How to calculate the limit? Here is my code:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var stickyTop = $('#aside1').offset().top;
  
  $(window).scroll(function() {
    var windowTop = $(window).scrollTop();
    var limit = $('footer').offset().top - $('#aside1').height();
  
    if (stickyTop &lt; windowTop) {
      $('#aside1').css({ position: 'fixed', top: '150px' });
    } else {
      $('#aside1').css('position','static');
    }
  
    if (limit &lt; windowTop) {
      var diff = limit - windowTop;
      $('#aside1').css({top: diff});
    }
  });</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    background: #aba;
  }
  header, main, footer {
    display: block;
    max-width: 740px;
    margin: 0 auto;
  }
  header {
    margin-bottom: 15px;
    font-size: 200%;
    background: #456;
    text-align: center;
  }
  header a {
    color: #fff;
  }
  article {
    display: block;
    float: left;
    width: 485px;
    height: 1000px;
    background: #fff;
  }
  aside {
    display: block;
    margin-left: 500px;
    box-shadow: 0 0 0 1px #cff inset;
    background: #cdc;
  }
  footer {
    position: relative;
    top: 15px;
    margin-bottom: 15px;
    clear: both;
    height: 800px;
    background: #456;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;header&gt;
    Sticky sidebar
  &lt;/header&gt;
  
  &lt;div style="clear:both;"&gt;&lt;/div&gt;
  &lt;main&gt;
    &lt;article id="article"&gt;&lt;h1&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio modi maiores repellat et, asperiores tempore! Provident velit illo, in quod ea explicabo, dignissimos dolorem voluptatibus, quisquam voluptas consectetur fugiat vel?&lt;/h1&gt;&lt;/article&gt;
    &lt;aside id="aside1"&gt;1&lt;br&gt;2&lt;br&gt;3&lt;br&gt;4&lt;br&gt;5&lt;br&gt;6&lt;br&gt;7&lt;br&gt;8&lt;br&gt;9&lt;br&gt;10&lt;br&gt;11&lt;br&gt;12&lt;br&gt;13&lt;br&gt;14&lt;br&gt;15&lt;br&gt;16&lt;br&gt;17&lt;br&gt;18&lt;br&gt;19&lt;br&gt;20&lt;/aside&gt;
  &lt;/main&gt;
  
  &lt;footer&gt;&lt;/footer&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>Sandbox: <a href="http://jsbin.com/yivomexixi/edit?html,output" rel="nofollow">http://jsbin.com/yivomexixi/edit?html,output</a></p>