3

I have a frame with an image tag inside, like a photo gallery

<div id="frame">
 <img src="yahoo.com/logo.gif" id="photo" />
</div>

With jQuery I'm going to dynamically change the img src to a different image URL. This causes the frame to jump in height as the image dimensions are different. It also cause a flash as the browser loads the image. It's a bad experience.

What'd I'd like to know if is possible, is whenever the img src is changed, is for jQuery to show a default loader, and then once the image is fully loaded, then show the image and remove the loader.

Any suggestions? hopefully a plugin? thanks

AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

2 Answers2

4

You could try something like this:

$('#frame > img').after('<img src="loading.jpg" />') // some preloaded "loading" image
                 .hide()
                 .attr('src','/some/new/value.jpg')
                 .one('load', function() {
                    $(this).fadeIn().next().remove();
                 });
  • the after()(docs) method to insert a "loading" image (should be preloaded)
  • the hide()(docs) method to hide the current image
  • the attr()(docs) method to change the src
  • the one()(docs) method to bind a load event that will be removed once the image is loaded
  • the fadeIn()(docs) method to give a nice fade in effect once the image has loaded
  • the next()(docs) method to get to the "loading" image
  • the remove()(docs) method to remove the "loading" image
user113716
  • 318,772
  • 63
  • 451
  • 440
0

You could probably preload the images, as described here: Preloading images with jQuery

If you don't want your frame div to jump in height, you will need to set a fix height on the div that will fit all image sizes.

Community
  • 1
  • 1
limc
  • 39,366
  • 20
  • 100
  • 145