4
votes

I got simple javscript function with play/pause action. Unfortunately he works only with onclick event. Now i need also change icon color when played mp3 ends. Now at the end icon color stay from playing audio. I need to change back to the color when audio is paused (lightgreen).

JavaScript

  function aud_play_pause(object) {
    var myAudio = object.querySelector(".xnine-player");
    var myIcon = object.querySelector(".control");
    if (myAudio.paused) {
      myIcon.className = "control icon-pause";
      myAudio.play();
    } else if (myAudio.onend) {
      myIcon.className = "control icon-play";
    } else {
      myIcon.className = "control icon-play";
      myAudio.pause();
    }
  }

HTML

    <p>
        <a href="javascript:void(0)" onclick="aud_play_pause(this)">

            <i class="control icon-play"></i>
            <audio class="xnine-player" 
                src="http://www.noiseaddicts.com/samples_1w72b820/29.mp3" 
            preload="auto"></audio>

        </a> - audio #1 
    </p>

    <p>
        <a href="javascript:void(0)" onclick="aud_play_pause(this)">

            <i class="control icon-play"></i>
            <audio class="xnine-player" 
                src="http://www.noiseaddicts.com/samples_1w72b820/2235.mp3" 
            preload="auto"></audio>

        </a> - audio #2 
    </p>

Here is JSFIDDLE

1

1 Answers

4
votes

You can use the ended event of the Audio API:

audio_element.addEventListener("ended", function() {

Here is what you should add to your code:

document.querySelectorAll('audio').forEach(function(el) {
  el.addEventListener("ended", function() { 
    this.parentElement.querySelector('.control').className = 'control icon-play';
  }, true);
})

This is the change to your jsfiddle:
https://jsfiddle.net/71an95pa/4/