Unable to stop sound when there are multiple instances of it on the same page

Unable to stop sound when there are multiple instances of it on the same page

This is an update to my last question which I've made some progress with the help of some members.

I've got multiple instances of the html5 audio player on my page, and I use the jQuery fadeIn() fadeOut() to determine which song to play. When clicking a link to a different page, I have the current playing sound fade out volume, then stop, then reset progress to 0 seconds, then the page (along with the audio player) fades out and the new page (along with that page's audio player) fades in. I'm able to fade out the volume, but I can't stop the music or reset the timer to 0 seconds for some reason:

  1. <script> $('.link').on('click', function(e){ $('audio').currentTime = 0; /*reset timer*/ displayNone(); /*fade out current page*/ $(this.getAttribute("href")).fadeIn(); /*fade in target page*/ stopAudio(); }); function displayNone() { $('.pagecontainer>div').fadeOut(); } function stopAudio() { //fade out any current audio $('audio').animate({volume: 0}, 1000); setTimeout(function(){('audio').pause()},1000) /*stop audio after fading out volume*/ } $('.sound').on('play', function () { $('audio').animate({volume: 1}, 100); /*reset volume to 100% after clicking play button on player*/ }); </script> .... .... <a href="page1" class="link">page 1</a> <a href="page2" class="link">page 2</a> <a href="page3" class="link">page 3</a> <div class="pagecontainer"> <div id="page1"> <audio controls class="sound"> <source src="music1.mp3"/> <source src="music1.ogg"/> </audio> </div> <div id="page2"> <audio controls class="sound"> <source src="music2.mp3"/> <source src="music2.ogg"/> </audio> </div> <div id="page3"> <audio controls class="sound"> <source src="music3.mp3"/> <source src="music3.ogg"/> </audio> </div> </div>

For example:
  • I'm currently on page1, with music1.mp3 already playing for 10 seconds

  • I click the link to page2 without stopping music1.mp3, and music1.mp3 volume fades out along with with page1, and page2 fades in successfully along with a new instance of the music player for music2.mp3

  • After let's say 10 seconds I click link for page1 to go back to page1

  • The player for music1.mp3 is still playing (progress is 20 seconds) and haven't stopped, but now with zero volume

I don't get why music1.mp3 is not resetting its timer to 0 seconds and stopping fully.

The code works if I only have 1 instance of the audio player (ie, say only page1 has an audio player, page2 and page3 contains no audio player and text only.

Is it something wrong with $('audio').pause() or $('audio').currentTime = 0; (or both) not registering when there are multiple instances of ('audio')?

Thanks!