We can change an image on hover in JavaScript by making use of the image src property along with the onmouseover and onmouseout events.




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


Let’s say I have the following HTML code:


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.

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 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://daztech.com/wp-content/uploads/example-img2.png";
};
function changeImg2(){
  document.getElementById("img1").src = "https://daztech.com/wp-content/uploads/2024/02/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:

Hover on the image below to change it.




Hopefully this article has helped you understand how to change an image on hover in JavaScript.

Categorized in:

JavaScript,

Last Update: May 3, 2024