views:

84

answers:

1

I need to load 2 or more images off screen and display them with a transition only when all of them are loaded.

I'm having some issues with load() Here is my function it shows a div with a loading message, when the img is loaded it hide the loadig message and call a function with the visual transition (transizione();)

 function load_img(sezione) {
  if (sezione==1)   {sfondo = "sfondo2.jpg"; footer = "footer1.jpg";} 
  else if (sezione==2) {sfondo = "sfondo3.jpg"; footer = "footer2.jpg";}
  else if (sezione==3) {sfondo = "sfondo4.jpg"; footer = "footer3.jpg";}
  else if (sezione==4) {sfondo = "sfondo5.jpg"; footer = "footer4.jpg";}

  $("#loading").fadeIn();

  $("#sfondo2").load(function () {
   $("#loading").hide();
   transizione();
     }).attr('src', 'img/'+sfondo);

 }

How can I modify it to call 2 images? I'm a bit confused with how load() works for images

Thanks

Giuseppe

A: 

The "load" function, for images, is used to set up an event handler. In other words, it lets you provide a function to be called when an image has completely loaded.

If you want to wait for more than one image to load, and when they are all loaded you want to do something, you can set up something like this:

var $images = $('#image1, #image2'), count = $images.length;
$images.load(function() {
  --count;
  if (count === 0) {
    // here the count is zero, so all images are ready
    transizione(); // ? whatever you want
  }
});

See? That makes all the images have the same "load" handler, and what it does is just count down until all the different images are ready (because the count will be zero).

Maybe I have not understood your need here, Gusepo.

Pointy
just a personal preference but I have never liked var $images = $('#image1, #image2'), count = $images.length; over var $images = $('#image1, #image2'); var count = $images.length; - on separate lines.
Mark Schultheiss
True - formatting for this environment is not necessarily what I'd do in real code.
Pointy
That's exactly what I'm trying to do, but I can't make it work properly, when you write var $images = $('#image1, #image2'), count = $images.length;are #image1 and #image2 IDs of img tags?When I run the function the 1st time it works, then "count" returns me some funny values like 3 or -2, -1Should I reset the values in some ways?ThanksG
Gusepo