Jimbly2
Jimbly2

Reputation: 227

Javascript and button toggling

just when I think I've sorted it... a small toggling question - this code is meant to toggle from Play to Stop when clicked, but it doesn't. I can't see any problems with the variables - but then I don't really know js very well. Can anyone see why this doesn't work? Code follows.. var selSound = 8000; //default to first sound. var play = false; //default to paused.

function selectSound(id) {
    selSound = id;
}

function togglePlay() {
    var a = document.getElementById(selSound);
    var b = document.getElementById("playbtn");
    play = !play;
    if (play) {
        b.value = "Stop Playing";
        a.play();
    }
    else {
        b.value = "Start Playing";
        a.pause();
    }
}

HTML:

<div style="text-align:center"><button id="playbtn" data-role="button"     onclick="togglePlay()" >Start Playing</button></div>

This is part of an iOS/html5 project and will be tested in Safari and iOS simulator. Thanks J

Upvotes: 1

Views: 2499

Answers (2)

Oybek
Oybek

Reputation: 7243

Why don't you use input type="button"?

var play = false;
function togglePlay() {

    var b = document.getElementById("playbtn");
    play = !play;
    if (play) {
        b.value = "Stop Playing";
    }
    else {
        b.value = "Start Playing";

    }
}

and html:

 <input type="button" id="playbtn" data-role="button" value="Start playing" onclick="togglePlay()" />

Demo

EDIT

With button you have to use innerText

var play = false;
function togglePlay() {

    var b = document.getElementById("playbtn");
    play = !play;
    if (play) {
        b.innerText = "Stop Playing";
    }
    else {
        b.innerText = "Start Playing";

    }
}

Demo

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382726

You are missing quotes:

var a = document.getElementById(selSound);

Should be:

var a = document.getElementById('selSound');

Upvotes: 1

Related Questions