Anonymous
Anonymous

Reputation: 47

On mouse hover, change picture in JavaScript

I have an image in my HTML code, and I want to make it so that when my mouse is hovering over the image, it will change to the other image, and when the mouse is not hovering over the image, it switches back to the default. How do I program this in a <script> tag?

Upvotes: 4

Views: 23624

Answers (4)

Moix Khan
Moix Khan

Reputation: 9

You can use the on mouse out for this. here is my Work on it.

<html>
<head>
</head>

<body>
 <script>

 function setnewimage() {
 document.getElementById("img2").src = "myquiz1.png";
 }
 function setnewimage1() {
 document.getElementById("img2").src = "myquiz2.png";
 }
 function setnewimage2() {
 document.getElementById("img2").src = "myquiz3.png";
 }
 function setnewimage3() {
 document.getElementById("img2").src = "pic33.png";
 }
 function setoldimage() {
 document.getElementById("img2").src = "myquiz1.png";
 }
 </script>
 <div>
 <img id="img2" src="" width="300">
 <br>
 <img id="img1" src="myquiz1.PNG" onmouseover="setnewimage()"
width="300" onmouseout="setoldimage()">
 <img id="img66" src="myquiz2.PNG" onmouseover="setnewimage1()"
width="300" height="200" onmouseout="setoldimage()">
 <img id="img87" src="myquiz3.PNG" onmouseover="setnewimage2()"
width="300" height="200" onmouseout="setoldimage()">
 <img id="img80" src="pic33.PNG" onmouseover="setnewimage3()"
width="300" height="200" onmouseout="setoldimage()">
 </div>
</body>
</html>

Upvotes: -1

lvr7
lvr7

Reputation: 159

var image = document.getElementById("image");

//Now, we need to add an Event Listener to listen when the image gets mouse over.

image.addEventListener('mouseover', function(){
  image.src = "path/to/newimage"
})
image.addEventListener('mouseout', function(){
    image.src = "path/to/otherimage"
  })

Upvotes: 0

Varis Bhalala
Varis Bhalala

Reputation: 123

You can use css for this like:

.react {

  background: url('../img/React_Monoo.png');
}

.react:hover {
  background: url('../img/React_Colored.png');
}

here react is a class name

Upvotes: 2

Aniket G
Aniket G

Reputation: 3514

No <script> tag necessary. Use onmouseover and onmouseout to change the image source.

onmouseover will execute an action when your mouse goes over the image. In this case, we use this.src to set the image src to another image.

onmouseout will execute an action when your mouse goes out of the image. In this case, we use this.src again to set the image to the default image.

<img title="Hello" src="https://static.independent.co.uk/s3fs-public/thumbnails/image/2017/09/12/11/naturo-monkey-selfie.jpg?w968h681" onmouseover="this.src='https://www.ctvnews.ca/polopoly_fs/1.4037876!/httpImage/image.jpg_gen/derivatives/landscape_1020/image.jpg'" onmouseout="this.src='https://static.independent.co.uk/s3fs-public/thumbnails/image/2017/09/12/11/naturo-monkey-selfie.jpg?w968h681'" />

Upvotes: 10

Related Questions