user1912899 user1912899 - 4 years ago 238
Javascript Question

this.src.replace img src for multiple images

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) />"


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) />"


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!

Answer Source

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) />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download