I am working with a div
that has any number of img
elements inside it. Right now, each img
has the following CSS:
#content > img {
display: none;
position: absolute;
top: 0px;
left: 0px;
}
And the images can be cycled-through with a function that shows and hides them in turn. While each image is loading, however, I'd like to display a "loading..." image. I'd like to use JavaScript/jQuery to swap the source of each incomplete image for the "loading..." image while still permitting it to load. What's a lean and mean way to do this?
$(function(){
$('<img>').attr('src','loading.gif'); // preload the "loading" image.
$('#content > img').each(function(){
var original = this.src;
var $this = $(this);
$this.attr('src','loading.gif'); // swap to loading image.
$('<img>').attr('src',original)// pre-load original.
.load(function(){
$this.attr('src',original); // swap it back when pre-load is done.
});
})
});