Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change image in button on click

I've got a button with an image inside that I want to swap when clicked. I got that part working, but now I also want it to change back to the original image when clicked again.

The code I'm using:

<button onClick="action();">click me<img src="images/image1.png" width="16px" id="ImageButton1"></button>

And the Javascript:

function action() {
  swapImage('images/image2.png');
};

var swapImage = function(src) {
  document.getElementById("ImageButton1").src = src;
}

Thanks in advance!

like image 251
JamesM Avatar asked May 19 '13 09:05

JamesM


People also ask

How can change background image of button click in HTML?

The default button in HTML can be changed to an image using CSS. The required button is selected using the respective CSS selector. The background property can then be set to include a background image and change the image type as required. The border of the button can also be removed to show only the image itself.

Can you add an image to a button?

Button with an ImageYou can include an <img> element inside your <button> element to display the image on the button. You can still add text to the button, resulting in a combination of image and text.


1 Answers

While you could use a global variable, you don't need to. When you use setAttribute/getAttribute, you add something that appears as an attrib in the HTML. You also need to be aware that adding a global simply adds the variable to the window or the navigator or the document object (I don't remember which).

You can also add it to the object itself (i.e as a variable that isn't visible if the html is viewed, but is visible if you view the html element as an object in the debugger and look at it's properties.)

Here's two alternatives. 1 stores the alternative image in a way that will cause it to visible in the html, the other doesn't.

<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}

window.addEventListener('load', mInit, false);

function mInit()
{
    var tgt = byId('ImageButton1');
    tgt.secondSource = 'images/image2.png';
}

function byId(e){return document.getElementById(e);}

function action() 
{
    var tgt = byId('ImageButton1');
    var tmp = tgt.src;
    tgt.src = tgt.secondSource;
    tgt.secondSource = tmp;
};

function action2()
{
    var tgt = byId('imgBtn1');
    var tmp = tgt.src;
    tgt.src = tgt.getAttribute('src2');
    tgt.setAttribute('src2', tmp);
}
</script>
<style>
</style>
</head>
<body>
    <button onClick="action();">click me<img src="images/image1.png" width="16px" id="ImageButton1"></button>
    <br>
    <button onClick="action2();">click me<img id='imgBtn1' src="images/image1.png" src2='images/image2.png' width="16px"></button>
    </body>
</html>
like image 200
enhzflep Avatar answered Sep 21 '22 01:09

enhzflep