Search code examples
javascriptjqueryaudio

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 $(this).

I really want something like this:

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

But I can't find any documentation on it?


Solution

  • 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="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <audio id="audio" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto"   controls></audio>

    The equivalent to this in plain JS would be:

    const audio = document.querySelector('audio');
    audio.addEventListener('playing', () => {
      console.log('playback started!');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <audio id="audio" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto"   controls></audio>