javascriptdom-eventspersistent

Simple JavaScript function to persistently change the state of a button onclick?


Does anyone have any simple JavaScript functions that persistently change the state of a button onclick? As in:

[button1] [button2] [button3]

Then, when you click button 1, something like this happens:

(((button1))) [button2] [button3]

Then, if you were to click button2, this would happen:

[button1] (((button2))) [button3]

Where the image associated with button 1 is changed, persistently.

I checked out this answer https://stackoverflow.com/a/4967732/73844 and this answer https://stackoverflow.com/a/7991898/738448 but am having trouble seeing how they fit together to do what I want to do. Any help would be appreciated.

Here is the code I've tried:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
#prog
{
    margin: 5px 85px;
    width: 200px;
    height: 40px;
    background:url(prog_off.png) no-repeat;
    border: 0;
}
</style>
<script type="text/javascript">
function changeImage() {
    test=document.getElementById("prog");
    test.backgroundImage="url(prog_on.png)";
}
</script>
</head>
<body>
<input type="button" id="prog" onClick="changeImage()" />
</body>
</html>

Solution

  • Are you looking for something like this?

    http://jqueryui.com/demos/button/radio.html

    If so, it'll be easier (and better since its tested across all browsers etc..) using jQuery UI's button widget instead of developing afresh.

    http://jqueryui.com/demos/button/#radio