I am trying to use a button to pause the audio element, and the function works fine except the alert()
function. The alert just pop up and stays on the top of the website forever.
here is my HTML code
<button id="threeSecTimer">3s</button>
<figcaption>Fire</figcaption>
<audio controls loop>
<source src="xxx" type="audio/mpeg" />
Your Browser doesn't support the audio
</audio>
<figcaption>Forest</figcaption>
<audio controls loop>
<source src="xxx" type="audio/wav" />
Your Browser doesn't support the audio
</audio>
here is js
var threeSecTimer = document.getElementById("threeSecTimer");
var allMusic = document.getElementsByTagName("audio");
function pause3s(e) {
setTimeout(function () {
for (var i = 0; i < allMusic.length; i ) {
if ((allMusic[i] = e.target)) {
allMusic[i].pause();
allMusic[i].currentTime = 0;
alert("time is up!");
}
}
}, 3000);
}
threeSecTimer.addEventListener("click", pause3s);```
CodePudding user response:
You have missed an =
in your if condition, change (allMusic[i] = e.target)
to (allMusic[i] == e.target)
CodePudding user response:
Your condition, (allMusic[i] == e.target)
will never be true since e.target is targeting the 3s button, and allMusic[i] is the audo control. That is assuming you changed the single = to a ==, otherwise the condition will always be true, which is not what you want either, but would lead to the alert button popping up twice, once for each audio control. And when the alert is clicked it should disappear, at least it did for me when I tried out your code.
Perhaps you can check HTML5 check if audio is playing? to target the audio that is playing.