How ...">

Changing the image for a button on hover?

Hi I have an HTML button that is configured as follows:

<input type="image" src="derp.png">

How the image is not assigned through CSS, how should I change it on hover?

+3
source share
5 answers

Something like the following will work (although not currently verified), this requires that the alternate image is stored in the custome attribute data-*, so that the script knows where to find it, and then saves the original srcin a similar data-*one to return it to mouseout:

var inputs = document.getElementsByTagName('input');

for (var i = 0, len = inputs.length; i < len; i++) {
    input = inputs[i];
    input.onmouseover = function(){
        this.setAttribute('data-orig-image',this.getAttribute('src'));
        this.src = this.getAttribute('data-alt-image');
    };
    input.onmouseout = function(){
        this.src = this.getAttribute('data-orig-image');
    };
}​

JS Fiddle demo .

Keep in mind that the above requires yours to inputbe in HTML form:

<input type="image" src="http://path.to/default/image.png" data-alt-image="http://path.to/mouseover/image.png" />​

, CSS, , , , input src:

input[type=image] {
    background-image: url(http://davidrhysthomas.co.uk/img/dexter.png);
    background-repeat: no-repeat;
    background-position: 50% 50%;
    width: 200px;
    height: 185px;
}
input[type=image]:hover,
input[type=image]:active,
input[type=image]:focus {
    background-image: url(http://davidrhysthomas.co.uk/img/mandark.png);
}​

JS Fiddle demo.

+1

:

<input type="image" src="derp.png" onMouseOver="this.src='aderp.png'" onMouseOut="this.src='derp.png'">

JSFiddle (demo): http://jsfiddle.net/E6xHr/

, .

+13

, :

1) CSS

input.change {
background-image:url(derp.png);
}

input.change:hover {
background-image:url(mouseover.png);
} 

( 'change' .)

2) JavaScript

<input type="image" src="derp.png" onmouseover="this.src='mouseover.png'" onmouseout="this.src='derp.png'">
+1

JavaScript CSS, jQuery. hover() jQuery.

jQuery script

$(document).ready(function() {
 $('#img1').hover(function() {
    $('#img1').attr('src','second_img.jpg');
  }, function() {
   // do something here
   alert('hovered out');
 });
});

HTML

<input id="img1" type="image" src="first_img.png">

. .

+1

My idea would be to put the image under the button and have alpha to switch the background image of the button to 0 so that you can see the image under.

0
source

All Articles