Reputation: 2255
I'm trying to load several images into a div named 'images', when they finish loading I want it to slidedown the div 'images' which will show the actual images that have just been loaded into it, and I'm having a little bit of trouble writing out exactly how to make that happen.
This is what I have so far, it's not quite right:
$('#button').click(function() {
var image=$('#images');
$("<img>", {
src: "http://www.klossal.com/images/klossviolins/home.jpg"
}).appendTo("#images");
$("<img>", {
src: "http://www.klossal.com/images/klossviolins/inventory.jpg"
}).appendTo("#images");
$("<img>", {
src: "http://www.klossal.com/images/klossviolins/services.jpg"
}).appendTo("#images");
if (image.get(0).complete) { image.slideDown(300); }
});
Upvotes: 1
Views: 1752
Reputation: 914
Try below code:
<script>
$(document).ready(function () {
$('#button').click(function() {
$('#theDiv').prepend('<img id="theImg" src="http://www.klossal.com/images/klossviolins/home.jpg" />')
$('#theDiv').prepend('<img id="theImg" src="http://www.klossal.com/images/klossviolins/inventory.jpg" />')
$('#theDiv').prepend('<img id="theImg" src="http://www.klossal.com/images/klossviolins/services.jpg" />')
$('#theDiv').prepend('<img id="theImg" src="http://www.klossal.com/images/klossviolins/services.jpg" />')
$('#theDiv').hide();
$('#theDiv').slideDown('slow', function() {
// Animation complete.
});
});
});
</script>
Upvotes: 0
Reputation: 6722
Just listen for image load
event. In the event handler count images and if the number of loaded images matches the toal number of requested images then start the show.
var imgCount = 0;
var image=$('#images');
$('#button').click(function() {
console.log("Loading...");
$("<img>", {
src: "http://www.klossal.com/images/klossviolins/home.jpg"
}).appendTo("#images").load(onImage);
$("<img>", {
src: "http://www.klossal.com/images/klossviolins/inventory.jpg"
}).appendTo("#images").load(onImage);
$("<img>", {
src: "http://www.klossal.com/images/klossviolins/services.jpg"
}).appendTo("#images").load(onImage);
});
function onImage(e)
{
console.log("Image loaded");
imgCount++;
if (imgCount == image.children().length)
{
image.slideDown(3000);
}
}
.load(function name)
means that we are attaching an event listener which will listen for load
event and once it happens the function will be executed.
onLoad(e){}
means that the function named onLoad
takes one argument - this argument is passed from event listener and it is an event
object.
Inside the function the e
can be used to detect the object which trigerred the event, to gater some date an more...
Upvotes: 1
Reputation: 683
There is a nice jQuery plugin that triggers an event after all images inside an element are loaded: http://desandro.github.com/imagesloaded/
See this example in Fiddle: http://jsfiddle.net/TFVc9/2/
$('#button').click(function() {
var image=$('#images');
//...
image.imagesLoaded( function() {image.slideDown(300)} );
});
Upvotes: 1