Javascript – Making JS buttons that toggle their image on click

buttonjavascripttoggle

I am doing something like this-

http://www.w3schools.com/html5/tryit.asp?filename=tryhtml5_video_js_prop

but I want to replace the buttons with images that toggle to another image when clicked. In other words, the Play button will change to a Pause button.

There are many tutorials that show how to do this with only one button but as soon as I add more buttons, the new ones don't work.

Any help appreciated!

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>

<body>


<script type="text/javascript">

function changeIt()
{
var theImg = document.getElementsByTagName('img')[0].src;

var x = theImg.split("/");
var t = x.length-1;
var y = x[t];

if(y=='btnPlay.gif')
{
document.images.PlayOrPause.src='btnPause.gif'
}
if(y=='btnPause.gif')
{
document.images.PlayOrPause.src='btnPlay.gif'
}



}

</script>

<a href="#" onclick="changeIt()"><img src='btnPause.gif' name='PlayOrPause' border='0' /></a>

Best Answer

Try this using input type image

HTML

<input type="image" src="play.png" class="play" onclick="toggle(this);"/>

CSS

.play, .pause {width:100px;height:100px;}

JS

function toggle(el){
    if(el.className!="pause")
    {
        el.src='pause.png';
        el.className="pause";
    }
    else if(el.className=="pause")
    {
        el.src='play.png';
        el.className="play";
    }

    return false;
}  ​

A fiddle is here. ​

Related Topic