Chud37 Chud37 - 2 years ago 151
jQuery Question

Trigger function when clicking play button on <audio>

I have my audio element:

<audio class='mp3audio' src='file.mp3'></audio>

And I want to perform a function or an action when the play button is clicked in jQuery. I've found lots of things for creating your own custom controls, but nothing to fire when the play button is clicked. The closest I've found is this, but then I can't use useful things like

I really want something like this:

$('audio.mp3audio').click(function () {
alert("you clicked play");

But I can't find any documentation on it?

Answer Source

You can hook to the playing event, so you can run the code no matter how the audio element is controlled; either from the play control, or manually through code. Try this:

$('audio').on('playing', function() {
  console.log('playback started!');
<script src=""></script>
<audio id="audio" src="" preload="auto"   controls></audio>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download