Delowar Hossain
Delowar Hossain

Reputation: 385

jQuery determine if a audio is finished playing and trigger function after that

I have generated audio links from a javascript file and I triggered audio play using jQuery. I want to trigger a function when audio is finished.

Here's my HTML.

<div id="audio-holder" class="text-center">

</div>

Dynamically creating element from javascript objects:

$.each( page15, function( key, value ) {
    $("#audio-holder").append(
          "<span class='word' data-audio-path='"+value.audio+"'>"+value.word+"</span>"
    )});

Here's player code:

$( ".word" ).each(function(index) {
     $(this).on("click", function(){
         var audioSrc = $(this).attr("data-audio-path");
         var audioElement = document.createElement('audio');
         audioElement.setAttribute('src', audioSrc);
         audioElement.play();

         // Here goes custom function
     });
});

Another problem is if I click one word its playing one audio and in the meantime if I click another audio plays along with previous audio. How can I stop previous audio when new audio starts.

Upvotes: 0

Views: 506

Answers (1)

Sifat Haque
Sifat Haque

Reputation: 6057

You can check the ended event and then do your stuff.

yourAudio.addEventListener("ended", function(){
     yourAudio.currentTime = 0;
     console.log("ended");
});

Upvotes: 1

Related Questions