Jquery – Change Image

Swap an image when a thumbnail is clicked using JQuery :

This simple example uses a progressive enhancement technique in which links to full-size images are “hijacked” by Javascript code that replaces the main image on the page with the full size version of the thumbnail.

Markup

The markup is pretty standard one. The important bits are…

  • The thumbnails are links to full size versions of the images. If a user does not have javascript, the links still go to the large image.
  • The links are given a “thumbnail” class which is used by jQuery to hijack their click event.
  • The main image is wrapped by a <div> element and given an id of “imageWrap”.
CSS

The “imageWrap” <div> is given a couple of CSS styles…

  • Fixed dimensions are used so that the layout does not collapse when an image is replaced.
  • The spinning AJAX loading graphic is added and removed by the Javascript, however, having it in the CSS will force it to be loaded by the user’s browser so that it is available in the browser cache.
Javascript

  1. ready() ensures that the links are not hijacked until the DOM has finished loading.
  2. live() will attach the handler to the click event of every link with the “thumbnail” class.
  3. The main image is hidden using hide() while the new image is being loaded.
  4. The spinning AJAX loading graphic is applied to the “imageWrap” <div> background using css()for the end user to see while the new image is being loaded.
  5. The var i = $(‘<img />’) selector creates a new <img> element, .attr(‘src’,this.href) sets the “src” attribute of this newly created <img> to the “href” of the link being hijacked, and then load()attaches the handler to the load-event fired when the new image has been loaded.
  6. In the handler for the image load-event, attr() is used to swap the “src” attribute of the main image on the page with the “src” of the newly loaded image. The key here is that the new image is now done loading.
  7. css() is used again to remove the AJAX loading graphic so that it is not visible while the new image is faded in.
  8. fadeIn() is used to slowly fade in the new image.
  9. return false; prevents the default handler for the link’s click event so that the browser is not redirected to the full size image.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.