jQuery image swap or How to replace an image with another one using jQuery

Swapping one image with another is probably one of the most used javascript techniques. Also Dreamweaver made “image replacement” even easier for non HTML/Javascript programmers by including this feature out of the box. One thing about Dreamweaver’s image swapping javascript is that it’s not the most beautiful javascript code. Well, as always with anything javascript related, jQuery is to the rescue.

jQuery makes dynamic image swapping a peace of cake. All you need to do to replace your image with another one is to replace its src attribute. The browser will take care of the rest.

Here is an example:

$("#myImage").attr("src", "path/to/newImage.jpg");

In the code above we are:

  1. Selecting an image to be replaced;
  2. Changing its src attribute to the new replacer image’s URL.

To avoid page jumping and improve user experience it is a good idea to preload your images before you swap them.