detect part of page
by lennyekberg
HTML
<div id="viewportMask"></div>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
CSS
ul {
margin: auto;
}
ul li {
width: 300px;
height: 30px;
background: silver;
float: left;
margin: 10px;
list-style:none;
}
ul li.middleviewport {
background:blue;
width: 400px;
}
#viewportMask {
position: fixed;
top: 30%;
bottom: 40%;
left: 0;
right: 0;
background: green;
opacity: 0.2;
}
.red_background{
background: red;
}
.silver_background{
background: blue;
}
JavaScript
$(document).ready(function () {
$(window).on('scroll', function () {
var windowHeight = $(window).height(),
gridTop = windowHeight * .3,
gridBottom = windowHeight * .6;
$('ul li').each(function () {
var thisTop = $(this).offset().top - $(window).scrollTop();
if (thisTop > gridTop && (thisTop + $(this).height()) < gridBottom) {
// $(this).css('background', 'red');
$(this).addClass('red_background');
} else {
//$(this).css('background', 'silver');
$(this).removeClass('red_background');
}
});
});
$(window).trigger('scroll');
});