Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing image for button on hover?

Tags:

html

css

forms

Hi I have a HTML button that is setup like this:

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

As the image is not assigned via CSS how am I meant to change it on hover?

like image 649
Dragan Marjanovic Avatar asked Dec 01 '22 22:12

Dragan Marjanovic


2 Answers

A very simple way:

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

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

There are much more unobtrusive ways to do this, but this will work.

like image 59
vimist Avatar answered Jan 11 '23 04:01

vimist


Something like the following would work (though currently untested), it requires the alternate image to be stored in a custome data-* attribute in order that the script knows where to find it, and then stores the original src in a similar data-* in order to put it back on 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.

Bear in mind the above requires your input to have the HTML form:

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

Edited to add a CSS option, which is somewhat imperfect unfortunately, and requires that the input has no image set in its src attribute:

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.

like image 42
David Thomas Avatar answered Jan 11 '23 04:01

David Thomas