title: jQuery – Adding a class at/after a specific point in scroll, with variable-length content above
body: <p>Fairly new to jQuery and JavaScript in general. I mocked up an example of my problem at <strong><a href="http://jsbin.com/alibi3/2/" rel="nofollow noreferrer">http://jsbin.com/alibi3/2/</a></strong> - with an explanation below.</p>
  
  <p>I have a div that, after a user scrolls past a certain point on the page, is assigned a class of "fixed" so it follows the user down the page. This works fine on its own.</p>
  
  <p>Problem is, the content above that div can be toggled to show/hide - and when it is shown, the fixed class is still being applied at the point it would have been if it was hidden, so it appears to 'jump'.</p>
  
  <p>How do I tell my fixed-class-adding function that the div above has been shown/hidden, and so adjust the point at which the 'fixed' class is added?</p>
  
  <p>Thanks.</p>
  
  <h2>HTML:</h2>
  
  <pre><code>&lt;div id="drawer"&gt;
      &lt;a href="#"&gt;Click here to toggle drawer&lt;/a&gt;
      &lt;p id="drawercontents"&gt;Here is the stuff in the drawer; hidden by default.&lt;/p&gt;
  &lt;/div&gt;
  &lt;div id="article"&gt;
      blah, blah...
  &lt;/div&gt;
  &lt;div id="nav"&gt;
      This should follow down the page once we scroll past the start of the article,
      and 'stick' back in place when we are back at the top.
  &lt;/div&gt;
  </code></pre>
  
  <h2>CSS:</h2>
  
  <pre><code>  #article {
      width: 400px;
      float: left;
      margin-right: 20px;
      padding: 20px;
      background: #eee;
    }
    #nav {
      width: 200px;
      float: left;
      background: #ff0;
      padding: 20px;
    }
    #drawer {
      width: 660px;
      padding: 20px;
      color:#fff;
      background: #000;
      margin-bottom: 10px;
    }
    .fixed { position: fixed; left: 460px; top: 0px; }
  </code></pre>
  
  <h2>JavaScript:</h2>
  
  <pre><code>$(document).ready(function() {
    $('#drawercontents').hide();
  
    $('#drawer a').click(function(e){
      e.preventDefault();
      $('#drawercontents').toggle('fast');
    });
  
    var top =$('#nav').offset().top - parseFloat($('#nav').css('marginTop').replace(/auto/, 0));
    $(window).scroll(function () {
      // what is the y position of the scroll?
      var y = $(window).scrollTop();    
      // whether that's below the start of article?
      if (y &gt;= top) {
        // if so, add the fixed class
        $('#nav').addClass('fixed');
      } else {
        // otherwise, remove it
        $('#nav').removeClass('fixed');
      }
    });
  });
  </code></pre>