We can use jQuery to swap an image on hover by making use of the image src property along with the jQuery hover() method.




Let’s see the full HTML code and jQuery for this below.


Let’s say we have the following HTML code:


To swap the image above to another image on hover, we can use the attr() method along with thw src property. We can change the src of #img1 from img.jpg to anotherImg.jpg using the following jQuery code below.

$("#img1").hover(function() {
  $("#img1").attr("src","anotherImg.jpg");
}, function(){
  $("#img1").attr("src","img.jpg");
});

If you are using WordPress, don’t forget to change the $ to jQuery as below:

jQuery("#img1").hover(function() {
  jQuery("#img1").attr("src","anotherImg.jpg");
}, function(){
  jQuery("#img1").attr("src","img.jpg");
});

Let’s see an interactive example of this below.

Swap an Image on Hover Using jQuery

To change the source of an image on user hover we can combine the src property with the jQuery hover() method.

Let’s say we have the following HTML, similar to our example from above.

Hover on the image below to change it.


We have two images, example-img1.png is a picture of gears and example-img2.png is the same image, but with different colors.

We will use the jQuery hover function to swap the images from the example-img1.png version to the example-img2.png version when the user moves their mouse over the image and off of it.

Here is the code below that will accomplish this:

$("#img1").hover(function() {
  $("#img1").attr("src","https://daztech.com/wp-content/uploads/example-img2.png");
}, function(){
  $("#img1").attr("src","https://daztech.com/wp-content/uploads/2024/02/example-img1.png");
});

The final code and output for using jQuery to swap images on hover is below:

Code Output:

Hover on the image below to change it.

Full Code:

Hover on the image below to change it.





Hopefully this article has helped you understand how to use jQuery to swap images on hover.

Categorized in:

jQuery,

Last Update: April 2, 2024