Toggle javascript functions

Asked

Viewed 110 times

6

In my code there is a button, which, when clicked, plays a song

<div class="botao" id="btn1"><audio id="audio1" controls loop="true" style=" visibility: hidden;">
  <source src="musica/song.wav" type="audio/wav">
Your browser does not support the audio element.
</audio></div>

But how do I make it, once it has started playing, it stop a song and vice versa, in JS? I tried the following:

var sng1 = document.getElementById("audio1"); 
var bt1 = document.getElementById("btn1");
btn1.onclick = onclick = function(event){
   sng1.play();

But I don’t know what to do to stop the music. Thanks in advance. : D

  • Hello Jvsierra, welcome to Sopt, I edited your question to adapt it to the site. Use the snippet only when it is a complete and verifiable example, otherwise use only "code sample" (the {} of the editor).

1 answer

8


The object also has a method pause, and a property paused to check if it is already paused. So you can do so:

var sng1 = document.getElementById("audio1"); 
var bt1 = document.getElementById("btn1");
btn1.onclick = function(event){
    if(sng1.paused) {    
       sng1.play();
    } else {
       sng1.pause();
    }
}

Demo

Browser other questions tagged

You are not signed in. Login or sign up in order to post.