Wes
Wes

Reputation: 59

Single button toggle for audio using vanilla javascript

I am trying to make a simple button to turn on and off my audio file.

Once I click play I can't turn it off.

I'm using an image as my button and div.onclick to spark the function.

The html audio tag has id audioPlay.

I use the global boolean playSound, initially set to false.

My script looks like this:

var playSound = false;
if (playSound != true) {
    audioButton.src = '../../testStuff/audioPlay.png';
    audio.onclick = function () {
        document.getElementById('audioPlay').play();
        playSound = true;
        console.log(playSound);
    }
}

if (playSound == true) {
    audioButton.src = '../../testStuff/audioStop.png';
    audio.onclick = function () {
        document.getElementById('audioPlay').pause();
        playSound = false;
    }
}

When I click on it the first time it works fine. It sets playSound to true.

However, when I go to click it a second time, nothing happens. Something is setting playSound back to false and I don't know why.

I've tried switching the ==true if statement above the false one, as well as rolling both if statements into a single onclick function but it still operates this way.

Any ideas?

Upvotes: 1

Views: 658

Answers (2)

hussin ali
hussin ali

Reputation: 1

//play is the name of the botton that u click to play the music and psuse    
const isplay;
play.addEventListener('click',()=>{
    const playmusic = ()=>{
        isplay = true;
        console.log('play music');
        music.play();
    };
const pausemusic = ()=>{
isplay = false;
music.pause();
};
if(isplay){
pausemusic();
}else{
playmusic();
};
)};

Upvotes: 0

Shannon Scott Schupbach
Shannon Scott Schupbach

Reputation: 1278

I think the issue is that you're adding two separate click handlers that are both being executed on each click. This results in playSound always being set to true, but then immediately being set back to false.

Instead, write a function called togglePlay that does something like the following, and set that as your click handler, but only once.


    function togglePlay () {
      if (playSound) {
        audioButton.src = '../../testStuff/audioStop.png';
        document.getElementById('audioPlay').pause();
        playSound = false;
      } else {
        audioButton.src = '../../testStuff/audioPlay.png';
        document.getElementById('audioPlay').play();
        playSound = true;
      }
    }

Upvotes: 1

Related Questions