I want to change the source of an image when hovering over it.
I've managed to do it for one image, by
<img id="image1" src="image1-grey.png" onmouseover=colorImage(this) />"
And:
function colorImage(x){
document.getElementById("image1").src = x.src.replace("grey", "color");
}
I have a dozen or so images - all in two versions, grey and color.
Now I guess I could repeat the function above for all the images individually, but there must be a cleaner way.
This is what I figured, but it doesn't work:
<img id="image1" src="image1-grey.png" onmouseover=colorImage(image1) />"
And:
function colorImage(x){
document.getElementById(x).src = this.src.replace("grey", "color");
}
This way, I thought, I'd only have one function for all the images. But no. Why not?
Thanks a lot in advance!
Since you're passing a reference to the image as a parameter, you don't need to use document.getElementById... you already have it!
function colorImage(x){
x.src = x.src.replace("grey", "color");
}
You can continue to call the function using your first way:
<img id="image1" src="image1-grey.png" onmouseover=colorImage(this) />
Looks like your problem is with image1
in the line below
onmouseover=colorImage(image1)
it needs to be in quotes like you are passing a string (shown below)
onmouseover=colorImage('image1')
The way your passing it now you are sending a javascript variable named image1
(which would be undefined
) instead of the string name you want "image1"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.