1
votes

I need to call a function when an HTML5 audio element stops playing. Specifically the function will reset the seek bar and change the pause icon to a play icon.

Here's my JavaScript:

var audio = document.getElementById('audio');

audio.addEventListener('ended', stopAudio);

function stopAudio() {
    audio.stop();
    $('.play-pause .play').show();
    $('.play-pause .pause').hide();
}

.. only the code inside is not executing once called. The audio is playing successfully and ending successfully, it's just not calling my function. What am I missing?

4
The code looks OK to me. Are you sure it's not running? Perhaps try a console.log() or similar in stopAudio(); - Lee Theobald
Does your <audio> element actually have id="audio"? Otherwise it looks fine -- ended is the correct event name. whatwg.org/specs/web-apps/current-work/#htmlaudioelement look for "Event handler" - leftclickben

4 Answers

0
votes

It is because you are using getElementById and passing audio when I think you mean to use getElementsByTagName, either that or you have the wrong id for the audio element.

0
votes

I needed:

audio.stop;

Instead of...

audio.stop();

Which fixed it :)

0
votes

The HTML Audio Element has no method stop(). The reason your event handler isn't "working" is because the line audio.stop(); throws an error and nothing below it will execute.

0
votes

Your code should look like below in order to detect if your audio has ended. There is no way to detect if it has been stopped but you can detect if it has ended or been paused. If you are looking for the code for when it's paused you replace the "ended" with "pause"

document.getElementById('audio').addEventListener("ended",function() {

$('.play-pause .play').show();
$('.play-pause .pause').hide();
}