Adam
Adam

Reputation: 11

Fade in multiple images in secquence once they have loaded

What I am trying to achieve is a grid of images (10x10) that firstly load after the rest of the page has finished loading, and secondly fade in 1 after another

i.e. (represents only one line)

----------
+---------
++--------
+++-------
++++------

etc... What I have so far is this:

<script type="text/javascript">
var loadingImage = false;
function LoadImage(imageName,imageFile)
{
  if ((!document.images) || loadingImage) return;
  loadingImage = true;
  if (document.images[imageName].src.indexOf(imageFile)<0)
  {
    document.images[imageName].src = imageFile;
  }
  loadingImage = false;
}
LoadImage('0','images/0.jpg');
</script>

With this image tag

<img class="fade" name="0" onLoad="LoadImage('1','images/1.jpg')" />

This gives me half the solution in as much as it loads all the images in sequentially, but I cant seem to add a fade to these images. The images are set up in an UL with 10 pictures in each LI, and 10 LI's in total = 100 images.

How can I fade these in? Also is there a way to print out all the images in a loop insted of having them manually written in, so the user doesnt have to go through and make sure every image tag is correctly named? (ive already got a batch image renamer)

I found This which is similar to what I need, but I couldnt work out how to get it to load the way I want. Thanks

Upvotes: 1

Views: 4990

Answers (1)

Nick Craver
Nick Craver

Reputation: 630379

Instead of what you have, you can do this, keep the markup simple:

<img class="fade" name="0" src="images/1.jpg" />

Then in your CSS just have them hidden initially:

.fade { display: none; }

Then on page load all the script you need to show them sequentially is this:

$(window).load(function() {
  $(".fade").each(function(i) {
    $(this).delay(400*i).fadeIn();
  });
});

window.onload as opposed to document.ready waits until all images are loaded as well, so just use that event for your .fadeIn() code. The default duration of any animation is 400ms, and in a .each() loop i is the index (0-based) of the element, so the first image fades in instantly (once all are loaded), the second is delayed 400ms (via .delay()), so it fades when the first is done, the third after that, etc. If you want to fade slower, say 1 second each, just pass that to both functions, like this:

$(this).delay(1000*i).fadeIn(1000);

Upvotes: 5

Related Questions