jQuery Web Page Design Tutorials

jQuery Replace Image Tutorial (Part 2)

Part 1 of jQuery Replace Image Tutorial

We already learned the syntax of jQuery attr() Method. Let's see how the selected element (boat image) can be replaced with other image when click on it.

Let's recall part of the HTML codes of the selected element (i.e. boat image).

<img src="boat.png" alt="boat" id="boat" width="203" height="190" />

Replace Image with jQuery attr() Method

How the following jQuery codes works?

The original boat image (boat.png) will replace with a new image (boat-2.png) when mouse pointer click on it.

$("#boat").click(function() {

newImgSrc = "boat-2.png";

$(this).attr("src", newImgSrc);

}

Result:

This is the original boat image (boat.png) when page load up.

jQuery replace image

The original boat image (boat.png) will be replaced with a new image (boat-2.png) when mouse pointer click on the boat layer.

jQuery replace image

Problem:

The above jQuery codes works fine if the image only change one time. In other words the new image (boat-2.png) cannot be changed back to the original image (boat.png).

How to fix this problem?

The following jQuery codes will allow the images to be changed to others whenever click on it.

$("#boat").click(function() {

var srcName = $(this).attr("src");

if (srcName =="boat.png") {
var newImgSrc = $(this).attr("src").replace(srcName, "boat-2.png");
} else {
var newImgSrc = $(this).attr("src").replace(srcName, "boat.png");
}

$(this).attr("src", newImgSrc);

}

The id of the boat layer will display when click on it.

Return Attribute Value of Selected Element with attr() Method

Let's learn something new with the jQuery attr() method. The jQuery attr() method also allows to return the value of attribute. The syntax is ahown as below:

This is the end of jQuery learn beginner tutorial.