3

Given the following markup:

<audio controls onclick="alert('hi')">
    <source src="/url/track.mp3" type="audio/mpeg">  
</audio>

I get no response from the onclick event. Seems like all the onclick events are bound to the player controls.

My goal is to run a separate function when the user hits "play".

2 Answers2

8

The onplay attribute is what you're looking for.

<audio onplay="myFunction()">...</audio>

Here's some article on w3schools about it

Alexander Mikhalchenko
  • 4,525
  • 3
  • 32
  • 56
0

You can place an invisible div over the audio element:

<script>
    function catchClick(){
        alert("hi");
    }
</script>

<div onclick="catchClick()" style="position:absolute;z-index:1;width:300px;height:30px;">
</div>
<audio controls>
    <source src="/url/track.mp3" type="audio/mpeg">
</audio>

Then, in the catchClick function you can pass the mouse clicks to the audio element via this method How to simulate a mouse click using javascript

Community
  • 1
  • 1
cantelope
  • 1,147
  • 7
  • 9