Search code examples
javascriptjqueryhtml5-audio

How to make users STOP the execution of an HTML5 audio autoplay file clicking anything on the page?


I'm working on a page that, on my client's request, loads playing a background soundtrack. Of course it's just for those users who are not navigating with audio autoplay disabled. So the simple piece of code used to start playing the music is something like the following:

<audio autoplay id="background-soundtrack">
  <source src="mytrack.mp3" type="audio/mpeg">
</audio>

I'd like to make music stop (even better: make it fade out in a matter of a few seconds) as soon as the user clicks anywhere on the page -- it should work tapping on mobile devices too.

Can you please suggesitng me a smart way to achieve my goal? It doesn't matter if it's pure JavaScript or jQuery.

Thanks!


Solution

  • try this jquery:

    $('document').on('click','body',function(){
      if ($('#background-soundtrack').paused == false){
        $('#background-soundtrack').animate({volume: 0}, 1500,
           //1500 duration time
           function(){ 
             $('#background-soundtrack').pause()
           });
      }
    });