Search code examples
htmlaudioplayback

Execute function when html audio player's play button is clicked


Is it possible to detect when the play button in the html5 audio player is clicked? For example:

<audio controls>
    <source src="music.mp3"/>
    <source src="music.ogg" />
</audio>
....
....
$('playbutton').on('click', function(e){
    //some functions
});

Solution

  • Sounds like (heh) you're looking for the play event.

    <audio controls id="player">
      <source src="music.mp3">
    </audio>
    
    <script>
      var player = document.getElementById("player");
      player.addEventListener("play", function () {
          console.log("it's go time");
      });
    </script>
    

    For a full list of the available events, at least according to the spec, check out the WHATWG doc