Fade on scroll

by lovromar

HTML

<div id="box1"></div>
<div id="box2"></div>


<br><br><br><br><br><br>
    <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>
    <br><br><br><br><br><br>
    <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>
        <br><br><br><br><br><br>
    <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>
            <br><br><br><br><br><br>
    <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>
                <br><br><br><br><br><br>
    <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>
                    <br><br><br><br><br><br>
    <p>I would like to find a much shorter, more elegant piece of code, but just can't quite work it out. Maybe...

CSS

#box1, #box2, #box3, #box4, #box5, #box6 {
    width: 100px;
    height: 100px;
    background: orange;
    margin:100px auto;
}
#box6 {
    margin-bottom:600px;
}

JavaScript

var box1Top = $('#box1').offset().top;
var box2Top = $('#box2').offset().top;


$(window).scroll(function () {
    if ((box1Top - $(window).scrollTop()) < 20) {
        $('#box1').stop().fadeTo(100, 0);
    } else {
        $('#box1').stop().fadeTo('fast', 1);
    }
    
    if ((box2Top - $(window).scrollTop()) < 20) {
        $('#box2').stop().fadeTo(100, 0);
    } else {
        $('#box2').stop().fadeTo('fast', 1);
    }
    
   
});