How to change button image on click?

horin picture horin · Sep 20, 2012 · Viewed 14.8k times · Source

I am using images and hrefs to create buttons. Code look like this:

<a href="http://www.zive.sk"><img src="res/images/zive.png" alt="Zive.sk" id="ziveCircle"></a>

Is there any way to change image src if user press button? Maybe some event handler which will determine that user has pressed image? It should act as normal button so when user press it and keep pressed it should change image src and when he releases the button then the href should be loaded (normal button behaviour).

PS: I cannot use css for this.

Answer

Daniel Li picture Daniel Li · Sep 20, 2012

This will change the button's image to your StackOverflow gravatar icon (change the URL accordingly):

HTML:

<a id="zive-anchor" href="javascript:void(0);">
    <img id="zive-img" src="res/images/zive.png" alt="Zive.sk" id="ziveCircle">
</a>​

Javascript:

document.getElementById('zive-anchor').onclick=function () {
    document.getElementById('zive-img').src = 
    "http://www.gravatar.com/avatar/ca2a5b453d7e221f50929cbf6d688e59?s=32&d=identicon&r=PG";
};​

JSFiddle:

http://jsfiddle.net/CsCSC/