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?
-
Please post your existing code and what you have tried so far.Aniket G– Aniket G2019-02-24 15:53:28 +00:00Commented Feb 24, 2019 at 15:53
Add a comment
|
4 Answers
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'" />
Comments
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"
})
Comments
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>