We can change an image on hover in JavaScript by making use of the image src property along with the onmouseover and onmouseout events.
<img src="img.jpg" onmouseover="changeImg1()" onmouseout="changeImg2()">
<script>
function changeImg1(){
//Swap image to the new one
};
function changeImg2(){
//Swap image back
};
</script>
Let’s see the full HTML code and JavaScript for this below.
Let’s say I have the following HTML code:
<div id="div1">
<img id="img1" src="img.jpg" onmouseover="changeImg1()" onmouseout="changeImg2()">
</div>
To swap the image above to another image on hover, we can use the src property. We can change the src of #img1 from img.jpg to anotherImg.jpg in our functions.
Here is what our functions would look like to change the image on hover.
function changeImg1(){
document.getElementById("img1").src = "anotherImg.jpg";
};
function changeImg2(){
document.getElementById("img1").src = "img.jpg";
};
Let’s see an interactive example of this below.
Change an Image on Hover Using JavaScript
To change the source of an image on user mouse hover we can combine the src property with onclick events.
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" onmouseover="changeImg1()" onmouseout="changeImg2()">
</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 have added two onclick events to the image that will run a function when the user moves their mouse over the image, and off of the image. We will swap the images from the example-img1.png version to the example-img2.png version when the user does this.
Here is the function below that will accomplish this:
function changeImg1(){
document.getElementById("img1").src = "https://theprogrammingexpert.com/wp-content/uploads/example-img2.png";
};
function changeImg2(){
document.getElementById("img1").src = "https://theprogrammingexpert.com/wp-content/uploads/example-img1.png";
};
The final code and output for changing an image on hover in JavaScript 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" onmouseover="changeImg1()" onmouseout="changeImg2()">
</div>
<script>
function changeImg1(){
document.getElementById("img1").src = "https://theprogrammingexpert.com/wp-content/uploads/example-img2.png";
};
function changeImg2(){
document.getElementById("img1").src = "https://theprogrammingexpert.com/wp-content/uploads/example-img1.png";
};
</script>
Hopefully this article has helped you understand how to change an image on hover in JavaScript.
Leave a Reply