I am working on animating a list of elements with CSS3 animations. Here is an example of the code:
.anim-slide-left {
animation: anim-slide-left 0.8s ease forwards;
-webkit-animation: anim-slide-left 0.8s ease forwards;
}
@-webkit-keyframes anim-slide-left {
0% {
transform: translateX(-500px);
-webkit-transform: translateX(-500px);
opacity: 0;
}
100% {
transform: translateX(0);
-webkit-transform: translateX(0);
opacity: 1;
}
}
/* there are more, but very similar */
My goal is to only animate visible elements with the 'animate' class when the page loads using JavaScript:
$(function() {
var $window = $(window);
var $toAnimate = $('.animate');
animate();
// check if element is on the viewport
function isElementVisible(elementToBeChecked)
{
var TopView = $(window).scrollTop();
var BotView = TopView + $(window).height();
var TopElement = elementToBeChecked.offset().top;
return ((TopElement <= BotView) && (TopElement >= TopView));
}
// add css animation class
function animate()
{
$toAnimate.each(function(i, el)
{
var $el = $toAnimate.eq(i);
if ($el.length && isElementVisible($el))
{
// remove already visible elements
$toAnimate.splice(i, 1);
// setting up animation effect
$el.addClass( $el.data('effect') );
$el.removeClass('animate');
}
});
}
});
However, I encountered a problem where only every second element is checked as visible. It should be checking each element individually like this:
https://i.sstatic.net/XdOGU.jpg
I want all elements to be animated correctly when they become visible while scrolling down the page, so I added this jQuery scroll function:
$window.scroll( function()
{
animate();
});
How can I make sure that every element is properly iterated through in this scenario?
EDIT:
After considering feedback from @T.J. Crowder, I updated the animate function by including a filter function suggested by @charlietfl:
$('.animate').filter( function( idx ) {
if( isElementVisible($(this)) )
{
$(this).addClass( $(this).data('effect') );
$(this).removeClass('animate');
}
});
This modification has resolved the issue. Thank you for your help.