Subscribing to an image loaded event

I recently was working on something where I needed to swap the src of an image, but then perform some specific javascript AFTER the new image was loaded, namely resize the dimensions a little. This may seem pretty simple, but took me a little research, along with trial and error to get a working solution, so hopefully it helps someone else. I often use jQuery on my smaller projects, so I’ll show how I accomplished this with that toolkit.

  1. First, I would need to listen to the load event of the image I was replacing the src of.
  2. Next, in order to trigger the handler, we need to actually change the src of the image
$('#my-image').load(function() {
    //Logic for w/e here, resizing, etc.
}).attr('src', myNewImageSrc);

The code itself is really simple, but it took me a few to realize that jQuery solved the problem by simply letting us listen to the load event of the image, and count on it being fired when the src changes, and finishes loading.

  • del.icio.us
  • Digg
  • Facebook
  • Reddit
  • Twitter
  • Yahoo! Buzz
and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Page optimized by WP Minify WordPress Plugin