Trigger css animation only once images have loaded

2.1k Views Asked by At

I'm using animate.css (FadeInDown) on some images and text on page entry. Runs fines locally, but on server it's not smooth at all because of all the images that need to be loaded (not massive file sizes, just many images).

The problem: animate.css kicks in (on page load), but while the images are half loading. I know I can 'display: none' the images and use JS/LazyLoad to show the images once loaded, but by then animate.css has already triggered.

So I think I need: A. to delay animate.css until exactly when the images are loaded/displayed or failing that, B. once you clicked a link to a page, it doesn't proceed to the next page until everything is fully loaded.

Anybody who can help?

animate.css

@keyframes fadeInDown {
  0% {
    opacity: 0;
    -webkit-transform: translateY(-20px);
    -ms-transform: translateY(-20px);
    transform: translateY(-20px);
  }

  100% {
    opacity: 1;
    -webkit-transform: translateY(0);
    -ms-transform: translateY(0);
    transform: translateY(0);
  }
}
2

There are 2 best solutions below

0
On

If you want to set animation on each image separately, when individual image is loaded you can do it something like this:

$("img").one("load", function() {
   $(this).addClass('fadeInDown');
}).each(function() {
  if(this.complete) $(this).load();
}); 
0
On

In jQuery, you can use $(document).ready() to execute a function when the DOM is loaded and $(window).on("load", handler) to execute a function when all other things are loaded as well, like images.

so basically, you can use this:

$(window).on("load", function(){
    // '#yourElement' this is the id of the html element you want to animate.
    // you can also use any other selector as well.
    $('#yourElement').addClass('animated fadeInDown');
});