title: jQuery fade out elements as they scroll off page, fade back as they scroll back on
body: <p>I want elements to fade out as they scroll off the top of the page, and then fade back in as they scroll back onto the page. I wrote some code that works, but I am looking for a more elegant solution. Here is the solution I have working on jsfiddle: <a href="http://jsfiddle.net/wmmead/JdbhV/3/" rel="noreferrer">http://jsfiddle.net/wmmead/JdbhV/3/</a></p>
  
  <p>I would like to find a much shorter, more elegant piece of code, but just can't quite work it out. Maybe something with an array and the each() method? If I put a class on the divs instead of an ID, it gets a lot shorter, but then they all fade out at once. I want each box to fade out as it scrolls off the page.</p>
  
  <p>HTML</p>
  
  <pre><code>&lt;div id="box1"&gt;&lt;/div&gt;
  &lt;div id="box2"&gt;&lt;/div&gt;
  &lt;div id="box3"&gt;&lt;/div&gt;
  &lt;div id="box4"&gt;&lt;/div&gt;
  &lt;div id="box5"&gt;&lt;/div&gt;
  &lt;div id="box6"&gt;&lt;/div&gt;
  </code></pre>
  
  <p>CSS</p>
  
  <pre><code>#box1, #box2, #box3, #box4, #box5, #box6 {
    width: 100px;
    height: 100px;
    background: orange;
    margin:100px auto;
  }
  #box6 {
    margin-bottom:600px;
  }
  </code></pre>
  
  <p>jQuery</p>
  
  <pre><code>var box1Top = $('#box1').offset().top;
  var box2Top = $('#box2').offset().top;
  var box3Top = $('#box3').offset().top;
  var box4Top = $('#box4').offset().top;
  var box5Top = $('#box5').offset().top;
  var box6Top = $('#box6').offset().top;
  
  $(window).scroll(function () {
  if ((box1Top - $(window).scrollTop()) &lt; 20) {
      $('#box1').stop().fadeTo(100, 0);
  } else {
      $('#box1').stop().fadeTo('fast', 1);
  }
  
  if ((box2Top - $(window).scrollTop()) &lt; 20) {
      $('#box2').stop().fadeTo(100, 0);
  } else {
      $('#box2').stop().fadeTo('fast', 1);
  }
  
  if ((box3Top - $(window).scrollTop()) &lt; 20) {
      $('#box3').stop().fadeTo(100, 0);
  } else {
      $('#box3').stop().fadeTo('fast', 1);
  }
  
  if ((box4Top - $(window).scrollTop()) &lt; 20) {
      $('#box4').stop().fadeTo(100, 0);
  } else {
      $('#box4').stop().fadeTo('fast', 1);
  }
  
  if ((box5Top - $(window).scrollTop()) &lt; 20) {
      $('#box5').stop().fadeTo(100, 0);
  } else {
      $('#box5').stop().fadeTo('fast', 1);
  }
  if ((box6Top - $(window).scrollTop()) &lt; 20) {
      $('#box6').stop().fadeTo(100, 0);
  } else {
      $('#box6').stop().fadeTo('fast', 1);
  }
  });
  </code></pre>