CSS: Change image src on img:hover

Hamed Kamrava picture Hamed Kamrava · Aug 3, 2013 · Viewed 508.1k times · Source

I need to change <img> source URL on hover.

I have tried this but won't work :

HTML

<img id="my-img" src="http://dummyimage.com/100x100/000/fff"/>

CSS

#my-img:hover {
    content: url('http://dummyimage.com/100x100/eb00eb/fff');
}

jsFiddle

Any help would be appreciated.

Update:

This only works for Webkit / Google Chrome.

Answer

Ashis Kumar picture Ashis Kumar · Aug 3, 2013

With only html and css, its not posible to change the src of image. If you do replace the img tag with div tag, then you might be able to change the image that is set as the background as like

div {
    background: url('http://dummyimage.com/100x100/000/fff');
}
div:hover {
    background: url('http://dummyimage.com/100x100/eb00eb/fff');
}

And if you think you can use some javascript code then you should be able to change the src of the img tag as below

function hover(element) {
  element.setAttribute('src', 'http://dummyimage.com/100x100/eb00eb/fff');
}

function unhover(element) {
  element.setAttribute('src', 'http://dummyimage.com/100x100/000/fff');
}
<img id="my-img" src="http://dummyimage.com/100x100/000/fff" onmouseover="hover(this);" onmouseout="unhover(this);" />