title: How do I use jQuery to fix a div to the top of the window only when the user scrolls down?
body: <p>I want the <code>my-sticky-element</code> to be pushed down by the top of the window when the user scrolls down, but only when the top of the window hits <code>my-sticky-element</code> as the user scrolls down. The code below does not seem to be pushing down the <code>my-sticky-element</code> (when I scroll down a few hundred pixels on my screen so that the top of the window collides with the element). I'm trying to do this in a SharePoint 2010 web part.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>//store the element
  var $cache = $('.my-sticky-element');
  
  //store the initial position of the element
  var vTop = $cache.offset().top - parseFloat($cache.css('margin-top').replace(/auto/, 0));
  $(window).scroll(function(event) {
    // what the y position of the scroll is
    var y = $(this).scrollTop();
    // whether that's below the form
    if (y &gt;= vTop) {
      // if so, ad the fixed class
      $cache.addClass('stuck');
    } else {
      // otherwise remove it
      $cache.removeClass('stuck');
    }
  });</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>.my-sticky-element.stuck {
    position: fixed;
    top: 0;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .3);
  }
  
  .my-sticky-element {
    background-color: grey;
    color: white;
    font-family: sans-serif;
    padding: 5px 20px;
    width: 200px;
  }
  
  .container {
    /*container for centering element*/
    margin: 100px auto;
    width: 200px;
  }</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;div class="container"&gt;
    &lt;div class="my-sticky-element"&gt;I want this item to be pushed down whenever the top of the window hits it. It should be stuck to the top of the window until the user scrolls back up and makes room for it to be visible.
    &lt;/div&gt;
  &lt;/div&gt;
  
  &lt;div style="height:1000px; width: 200px; background-color: yellow;"&gt;&lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>