How to change source of <img> tag on hover?

HtmlCss

Html Problem Overview


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.

Html Solutions


Solution 1 - Html

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

Solution 2 - Html

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/

Solution 3 - Html

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.

Solution 4 - Html

I had a similar problem but my solution was to have two images, one hidden (display:none) and one visible. On the hover over a surrounding span, the original image changes to display:none and the other image to display:block. (Might use 'inline' instead depending on your circumstances)

This example uses two span tags instead of images so you can see the result when running it here. I didn't have any online image sources to use unfortunately.

#onhover {
  display: none;
}
#surround:hover span[id="initial"] {
  display: none;
}
#surround:hover span[id="onhover"] {
  display: block;
}

<span id="surround">
    <span id="initial">original</span>
    <span id="onhover">replacement</span>
</span>

Solution 5 - Html

What you could do is cheat a little bit by setting width and height to 0 to hide the actual image and apply some CSS to do what you want:

#aks {
    width:0px;
    height:0px;
    background:url('http://dummyimage.com/100x100/000/fff');
    padding:50px;
}

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

And the padding making the img tag the size you want it to have (half the size of your actual image).

Fiddle

Solution 6 - Html

Concerning semantics, I do not like any solution given so far. Therefore, I personally use the following solution:

.img-wrapper {
  display: inline-block;
  background-image: url(https://www.w3schools.com/w3images/fjords.jpg);
}

.img-wrapper > img {
  vertical-align: top;
}

.img-wrapper > img:hover {
  opacity: 0;
}

<div class="img-wrapper">
  <img src="https://www.w3schools.com/w3css/img_lights.jpg" alt="image" />
</div>

This is a CSS only solution with good browser compatibility. It makes use of an image wrapper that has a background which is initially hidden by the image itself. On hover, the image is hidden through the opacity, hence the background image becomes visible. This way, one does not have an empty wrapper but a real image in the markup code.

Solution 7 - Html

I have one more solution. If anybody uses AngularJs : http://jsfiddle.net/ec9gn/30/

<div ng-controller='ctrl'>
    <img ng-mouseover="img='eb00eb'"  ng-mouseleave="img='000'"
         ng-src='http://dummyimage.com/100x100/{{img}}/fff' />
</div>

The Javascript :

function ctrl($scope){
    $scope.img= '000';
}

No CSS ^^.

Solution 8 - Html

Fiddle

Agree with AshisKumar's answer,
there is a way to change image url on mouse over by using jQuery functionality as below:

$(function() {
  $("img")
    .mouseover(function() { 
        var src = $(this).attr("src").match(/[^\.]+/) + "over.gif";
        $(this).attr("src", url1); //URL @the time of mouse over on image
    })
    .mouseout(function() {
        var src = $(this).attr("src").replace("over", "");
        $(this).attr("src", url2); //default URL
    });
 });

Solution 9 - Html

I had similar problem - I want to replace picture on :hover but can't use BACKGRUND-IMAGE due to lack of Bootstrap's adaptive design.

If you like me only want to change the picture on :hover (but not insist of change SRC for the certain image tag) you can do something like this - it's CSS-only solution.

HTML:

<li>
  <img src="/picts/doctors/SmallGray/Zharkova_smallgrey.jpg">
  <img class="hoverPhoto" src="/picts/doctors/Small/Zharkova_small.jpg">
</li>

CSS:

li { position: relative; overflow: hidden; }
li img.hoverPhoto {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  opacity: 0;
}
li.hover img { /* it's optional - for nicer transition effect */
  opacity: 0;
  -web-kit-transition:	opacity 1s ease;
  -moz-transition:	opacity 1s ease;li 
  -o-transition:	opacity 1s ease;
  transition:	opacity 1s ease;
}
li.hover img.hoverPhoto { opacity: 1; }

If you want IE7-compatible code you may hide/show :HOVER image by positioning not by opacity.

Solution 10 - Html

Since you can't change the src with CSS: If jQuery is an option for you, check this fiddle.

Demo

$('#aks').hover(
    function(){
      $(this).attr('src','http://dummyimage.com/100x100/eb00eb/fff')
    },
    function(){
      $(this).attr('src','http://dummyimage.com/100x100/000/fff')
    }
)

It's basically using the .hover() method... it takes two functions to make it work. When you enter the hover and when you exit it.

We are using the .attr (short for attribute) to change the src attribute.

It's worth to note that you need the jQuery library included like in the fiddle to make this work.

Solution 11 - Html

You cannot change the img src using css. You can use the following pure css solution though. HTML:

<div id="asks"></div>

CSS:

#asks {
  width: 100px;
  height: 100px;
  background-image: url('http://dummyimage.com/100x100/0000/fff');
}

#asks:hover {
  background-image: url('http://dummyimage.com/100x100/eb00eb/fff');
}

Or, if you don't want to use a div with a background image, you can use a javascript/jQuery solution. Html:

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

jQuery:

$('#asks')
  .mouseenter(function(){$('#asks').attr('src', 'http://dummyimage.com/100x100/eb00eb/fff');})
  .mouseleave(function(){$('#asks').attr('src', 'http://dummyimage.com/100x100/000/fff');});

Solution 12 - Html

Personally, I would go with one of the JavaScript / jQuery solutions. Not only does this keep your HTML semantic (i.e., an image is shown as an img element with it's usual src image defined in the markup), but if you use a JS / jQuery solution then you will also be able to use the JS / jQuery to preload your hover image.

Preloading the hover image will mean there is likely to be no download delay when the user hovers over the original image, resulting in your site behaving much more professionally.

It does mean you have a dependency on JS, but the tiny minority that don't have JS enabled are probably not going to be too fussed - and everyone else will get a better experience... and your code will be good, too!

Solution 13 - Html

You can't change img tag's src attribute using CSS. Possible using Javascript onmouseover() event handler.

HTML:

<img id="my-img" src="http://dummyimage.com/100x100/000/fff" onmouseover='hover()'/>

Javascript:

function hover() {
  document.getElementById("my-img").src = "http://dummyimage.com/100x100/eb00eb/fff";
}

Solution 14 - Html

For this you can use below code

  1. html

  2. css

    #aks { width:100px; height:100px;

         background-image:url('http://dummyimage.com/100x100/000/fff');}
    

    #aks:hover { background-image:url('http://dummyimage.com/100x100/eb00eb/fff';);

    }

Solution 15 - Html

On older browsers, :hover only worked on <a> elements. So you'd have to do something http://jsfiddle.net/ec9gn/78/">like this to get it to work.

<style>
a#aks
{
    width:100px;
    height:100px;
    display:block;
}

a#aks:link
{
  background-image: url('http://dummyimage.com/100x100/000/fff');
}

a#aks:hover
{
  background-image: url('http://dummyimage.com/100x100/eb00eb/fff');
}
</style>

<a href="#" id="aks"></a>

Solution 16 - Html

The following code works at both Chrome and Firefox

<a href="#"><img src="me-more-smile.jpg" onmouseover="this.src='me-thinking-about-a-date.jpg'" onmouseout="this.src='me-more-smile.jpg'" border="0" alt=""/></a>

Solution 17 - Html

Try This Code.

   .card {

            width: 200px;

            height: 195px;

            position: relative;

            display: inline-block;

        }

        .card .img-top {

            display: none;

            position: absolute;

            top: 0;

            left: 0;
           
            z-index: 99;
width:200px;
        }

        .card:hover .img-top {

            display: inline;

        }

 <!DOCTYPE html>

    <html lang="en">

    <head>

    <title>Image Change on Hover with CSS</title>

 
    </head>

    <body>

        <div class="card">

            <img src="http://www.dhresource.com/200x200s/f2-albu-g5-M00-EC-97-rBVaJFkAobCAHD9XAADvz9DDocA266.jpg/diy-wall-stickers-home-decor-nature-colorful.jpg" alt="Card Back" style="width:200px">

            <img src="https://s-media-cache-ak0.pinimg.com/236x/31/17/98/3117987a0be0a7d8976869aabf54d2d7.jpg" class="img-top" alt="Card Front">

        </div>

    </body>

    </html>

Solution 18 - Html

Heres a pure CSS solution. Put the visible image in the img tag, put the second image as a background in the css, then hide the image on hover.

.buttons{
width:90%;
margin-left:5%;
margin-right:5%;
margin-top:2%;
}
.buttons ul{}	
.buttons ul li{
display:inline-block;
width:22%;
margin:1%;
position:relative;
}
.buttons ul li a p{
position:absolute;
top:40%;
text-align:center;
}	
.but1{
background:url('scales.jpg') center no-repeat;
background-size:cover;
}
.but1 a:hover img{
visibility:hidden;
}	
.but2{
background:url('scales.jpg') center no-repeat;
background-size:cover;
}
.but2 a:hover img{
visibility:hidden;
}	
.but3{
background:url('scales.jpg') center no-repeat;
background-size:cover;
}
.but3 a:hover img{
visibility:hidden;
}	
.but4{
background:url('scales.jpg') center no-repeat;
background-size:cover;
}	
.but4 a:hover img{
visibility:hidden;
}		 	

<div class='buttons'>
<ul>
<li class='but1'><a href='#'><img src='scalesb.jpg' height='300' width='300' alt='' /><p>Blog</p></a></li>
<li class='but2'><a href='#'><img src='scalesb.jpg' height='300' width='300' alt='' /> <p>Herrero</p></a></li>
<li class='but3'><a href='#'><img src='scalesb.jpg' height='300' width='300' alt='' /><p>Loftin</p></a></li>
<li class='but4'><a href='#'><img src='scalesb.jpg' height='300' width='300' alt='' /><p>Contact</p></a></li>
</ul>
</div>
 

Solution 19 - Html

The best way to change src for image is:

<img src='willbehidden.png' style="width:0px; height:0px; padding: 8px; background: url(newimage.png);">

See live demo: http://www.audenaerde.org/csstricks.html#imagereplacecss

Enjoy!

Solution 20 - Html

There is another simple way using HTML and CSS only!

Just wrap your <img> tag with div like so:

<div class="image-wrapper">
    <img src="http://dummyimage.com/100x100/000/fff">
</div>

Then, in your CSS file hide the img and set the background image for the wrapping div element:

.image-wrapper:hover {
    background-image: url(http://dummyimage.com/100x100/eb00eb/fff);
    background-size: contain;
    background-repeat: no-repeat;
}

.image-wrapper:hover img {
    display: none;
}


Et voilà!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHamed KamravaView Question on Stackoverflow
Solution 1 - HtmlAshis KumarView Answer on Stackoverflow
Solution 2 - HtmlSurya R PraveenView Answer on Stackoverflow
Solution 3 - HtmljcruzView Answer on Stackoverflow
Solution 4 - HtmlMichaelCView Answer on Stackoverflow
Solution 5 - HtmlputvandeView Answer on Stackoverflow
Solution 6 - HtmlAnonymousView Answer on Stackoverflow
Solution 7 - HtmlChalisiView Answer on Stackoverflow
Solution 8 - HtmlNaveen Kumar AloneView Answer on Stackoverflow
Solution 9 - Htmle-kinstView Answer on Stackoverflow
Solution 10 - HtmlsulfureousView Answer on Stackoverflow
Solution 11 - HtmlPatrick KostjensView Answer on Stackoverflow
Solution 12 - Htmlban-geoengineeringView Answer on Stackoverflow
Solution 13 - HtmlPraveenView Answer on Stackoverflow
Solution 14 - HtmlHiren gardhariyaView Answer on Stackoverflow
Solution 15 - HtmlboboboboView Answer on Stackoverflow
Solution 16 - HtmlManishView Answer on Stackoverflow
Solution 17 - HtmlSunil RajputView Answer on Stackoverflow
Solution 18 - Htmluser3686007View Answer on Stackoverflow
Solution 19 - HtmlAlaa.KhView Answer on Stackoverflow
Solution 20 - HtmlmcgtrtView Answer on Stackoverflow