We can use jQuery to swap an image on hover by making use of the image src property along with the jQuery hover() method.
<img id="img1" src="img.jpg">
<script>
$("#img1").hover(function() {
//Swap image to the new one
}, function(){
//Swap image back
});
</script>
Let’s see the full HTML code and jQuery for this below.
Let’s say we have the following HTML code:
<div id="div1">
<img id="img1" src="img.jpg">
</div>
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.
<style>#img1 { height:100px; }</style><div id="div1">
<p>Hover on the image below to change it.</p>
<img id="img1" src="https://theprogrammingexpert.com/wp-content/uploads/example-img1.png">
</div>
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://theprogrammingexpert.com/wp-content/uploads/example-img2.png");
}, function(){
$("#img1").attr("src","https://theprogrammingexpert.com/wp-content/uploads/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:
<style>#img1 { height:100px; }</style><div id="div1">
<p>Hover on the image below to change it.</p>
<img id="img1" src="https://theprogrammingexpert.com/wp-content/uploads/example-img1.png">
</div>
</div>
<script>
$("#img1").hover(function() {
$("#img1").attr("src","https://theprogrammingexpert.com/wp-content/uploads/example-img2.png");
}, function(){
$("#img1").attr("src","https://theprogrammingexpert.com/wp-content/uploads/example-img1.png");
});
</script>
Hopefully this article has helped you understand how to use jQuery to swap images on hover.
Leave a Reply