I am trying to change the color of elements when they are between 30% and 60% of the viewport.
So I have this grid of elements stacking side
Improved @Tushar's solution to make it work even after a resize of the window (a recalculation of the viewport is necessary each time, not only at the beginning), and to make it start already highlighted, without the need to scroll.
Also improved a bit the graphic of the example to highlight the interested area.
Running demo
$(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');
} else {
$(this).css('background', 'silver');
}
});
});
$(window).trigger('scroll');
});
ul {
margin: auto;
}
ul li {
width: 300px;
height: 10px;
background: silver;
float: left;
margin: 10px;
list-style: none;
}
ul li.middleviewport {
background: red;
}
#viewportMask {
position: fixed;
top: 30%;
bottom: 40%;
left: 0;
right: 0;
background: red;
opacity: 0.2;
}