title: Change Div Css on document scroll
body: <p>I want to div position to be fixed when document scroll and that div reached to 50px from top.</p>
  
  <p>Please check the code below</p>
  
  <p>HTML</p>
  
  <pre><code>&lt;div id="main"&gt;
      &lt;div id="nav"&gt;&lt;/div&gt;
  &lt;div id="left"&gt;&lt;/div&gt;
  
  &lt;div id="right"&gt;
      &lt;div id="box1"&gt;&lt;/div&gt;
      &lt;div id="box2"&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>CSS</p>
  
  <pre><code>#main{ overflow:hidden; width:600px; height:900px; background:#afaaac; margin:0; padding:0; }
  
  #nav{ width:600px; height:40px; background:#15bc44; position:fixed; margin:0; padding:0;}
  
  #left{ overflow:hidden; width:400px; height:900px; background:#18769e; float:left; }
  
  #right{ overflow:hidden; width:200px; height:900px; background:#bc1544; float:right; }
  
  #box1{ float:right; width:150px; height:200px; display:block;background:#e34d2a; margin-bottom:20px; }
  
  #box2{ float:right; width:150px; height:200px; display:block;background:#e34d2a; margin-bottom:20px; }
  
  .box2{ position:fixed; margin-left:50px; margin-top:50px; }  
  </code></pre>
  
  <p>JS</p>
  
  <pre><code>$(document).ready(function() {
      var s = $("#box2");
      var pos = s.position();                   
      $(window).scroll(function() {
          var windowpos = $(window).scrollTop() ;
          //s.html("Distance from top:" + pos.top + "&lt;br /&gt;Scroll position: " + windowpos);
          if (windowpos &gt;= pos.top) {
              s.addClass("box2");
          } else {
              s.removeClass("box2");
          }
      });
  
  });
  </code></pre>
  
  <p>This work but it will go to the top of the document and jump back 50px.</p>
  
  <p>I also tried changing</p>
  
  <p><code>$(window).scroll(function() {</code> to </p>
  
  <pre><code>$(window).scroll(function() &gt; 50 {
  </code></pre>
  
  <p>and</p>
  
  <p><code>if (windowpos &gt;= pos.top) {</code> to <code>if (windowpos &gt;= 50) {</code></p>
  
  <p>This all seems make position jump around. Please check the JSFiddle below</p>
  
  <p><a href="http://jsfiddle.net/uGw2Z/2/" rel="nofollow">http://jsfiddle.net/uGw2Z/2/</a></p>
  
  <p>If anyone can point me out the correct way to do this, i will really appropriate it.</p>