CSS: Change image src on img:hover

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


I have modified few changes related to Patrick Kostjens.

<a href="#">
<img src="http://icons.iconarchive.com/icons/fasticon/angry-birds/128/yellow-bird-icon.png" 
onmouseover="this.src='http://icons.iconarchive.com/icons/fasticon/angry-birds/128/red-bird-icon.png'"
onmouseout="this.src='http://icons.iconarchive.com/icons/fasticon/angry-birds/128/yellow-bird-icon.png'"
border="0" alt=""/></a>

DEMO

http://jsfiddle.net/ssuryar/wcmHu/429/


Here is an alternate approach using pure CSS. The idea is to include both the images in the HTML markup and have these displayed or hidden accordingly on :hover

HTML

<a>
   <img src="https://cdn4.iconfinder.com/data/icons/imoticons/105/imoticon_15-128.png" /> 
   <img src="https://cdn4.iconfinder.com/data/icons/imoticons/105/imoticon_12-128.png" />
</a>

CSS

a img:last-child {
  display: none;  
}
a:hover img:last-child {
  display: block;  
}
a:hover img:first-child {
  display: none;  
}

jsfiddle: https://jsfiddle.net/m4v1onyL/

Note that the images used are of the same dimensions for proper display. Also, these images file sizes are quite small so loading multiple is not an issue in this case but may be if you are looking to toggle display of large sized images.

Tags:

Html

Css