Erika Danis
Erika Danis

Reputation: 17

jquery load multiple images after they have all finished loading

I have a function that gets called from an onclick event for example

<a href="#" onclick="changeImages()">load new</a> 

This function basically changes 5 images that are layered on top of each other:

    function changeImages(){
    document.getElementById("ins5").src="image5.png";
    document.getElementById("ins4").src="image4.png";
    document.getElementById("ins3").src="image3.png";
    document.getElementById("ins2").src="image2.png";
    document.getElementById("ins1").src="image1.png";       
}

What i would like is to display a LOADING animated gif while they all load. Once they have all finished loading then Fade them in. I have searched everywhere and cant find anything that works.

Many Thanks!

Upvotes: 0

Views: 6061

Answers (4)

Ohgodwhy
Ohgodwhy

Reputation: 50808

use jQuery. You can attach the .load parameter as a callback function.

function changeImages(){
  $("#ins5").prop('src','image5.png');
  $("#ins4").prop('src','image4.png');
  $("#ins3").prop('src','image3.png');
  $("#ins2").prop('src','image2.png');
  $("#ins1").prop('src','image1.png');
  $("#ins5, #ins4, #ins3, #ins2, #ins1").load(function(){
    //This is ourcallback. Once our images have loaded, we display an alert
    alert("loaded!");
  });
}

Upvotes: 3

Siva Charan
Siva Charan

Reputation: 18064

  1. Place a <div id="loadingImg" class="Img"> with Loading Image through CSS class
  2. Using Jquery, once the images are loaded then you can replace the <div id="loadingImg"> with your HTML.
  3. Replacing the existing div can be done using replaceWith() function

Upvotes: 0

Simon Edstr&#246;m
Simon Edstr&#246;m

Reputation: 6619

Attatch a eventhandler to the elements and check the loaded event.

http://api.jquery.com/load/

Upvotes: 0

Koen Peters
Koen Peters

Reputation: 12916

Check out the Image JavaScript Object. (http://www.w3schools.com/jsref/dom_obj_image.asp) It has some methods that you can poll to see it they are done loading. Using the setTimeout function you can loop over all Image objects, check if they are done and display the status to the user.

Or you can copy and paste one of the million scripts available on the net. Like this: Progress image while page is loaded

Upvotes: 0

Related Questions