Saturday, April 11, 2009

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.

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

6 comments:

  1. Thank you very much, this was helpful to me

    ReplyDelete
  2. thnks.......working fine.


    syam

    ReplyDelete
  3. I have an image that onclick togles between 2 images.
    my problem is that I need that image (with the same funtion) to apear several times in my page, but when I click on of the other images, it changes only the first one, when it shoud shange the one I'm clicking on. how can I make it work?

    ReplyDelete
  4. this is not helpful when you are new in jquery...

    ReplyDelete