Reputation: 86
I have a container with multiple rows of divs I want to animate in sequentially from left to right with a short time offset between each item, but only when the row is in the viewport on scroll. I do not want to group them into rows in the html since the items need to be 4 items per row, 3 items per row ect... based on screen size.
I basically want to do the below code but only on the row in the viewport and when scrolled down the page, animate the next row in the viewport ect...
$('.gallery-item').each(function(i){
$(this).delay((i++) * 200).fadeTo(400, 1);
});
To see the effect I'm looking to achieve take a loot at firstborn studios work page http://www.firstborn.com/work/featured
Any help would be greatly appreciated.
Upvotes: 0
Views: 365
Reputation: 17350
Why not simply add a line to check if the element is outside the viewport? We can assume that all the elements in the viewport are before the elements outside the viewport (hopefully), so you can do this:
$('.gallery-item').each(function(i){
if($(this).offset().top > window.innerHeight)
return false;
$(this).delay((i++) * 200).fadeTo(400, 1);
});
We simply cancel the loop once an element is outside the viewport. You could even do a double check if you want to so it will do it for al elements inside the viewport regardless of its position in the flow:
$('.gallery-item').each(function(i){
if(
$(this).offset().top < window.scrollTop + window.innerHeight
&& $(this).offset().top + $(this).height() > window.scrollTop
) $(this).delay((i++) * 200).fadeTo(400, 1);
});
This will only execute if the elements top is inside the viewport, or its bottom is.
Upvotes: 2