Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's one way to do it:</p> <pre><code>var lastPlay, lastSelected, Audios = []; $('.playAudio').each(function(i){ var Audio = {}; Audios[i] = Audio; Audio.audio = $(this).find('audio').get(0); Audio.playing = false; $(this).hover(function() { if (Audio.playing) { $(this).css({backgroundPosition: '-60px -60px'}); } else { $(this).css({backgroundPosition: '0px -60px'}); } },function() { if (Audio.playing) { $(this).css({backgroundPosition: '-60px 0'}); } else { $(this).css({backgroundPosition: ''}); } }); $(this).click(function(){ if (Audio.playing) { Audio.playing = false; $(this).css({backgroundPosition: '0 60px'}); Audio.audio.currentTime = 0; Audio.audio.pause(); } else { if (lastPlay &amp;&amp; Audios[lastPlay]) { Audios[lastPlay].audio.pause(); Audios[lastPlay].playing = false; } Audio.playing = true; $(this).css({backgroundPosition: '-60px -60px'}); Audio.audio.play(); lastPlay = i; lastSelected = $(this); } }); }); </code></pre> <p>I've changed your script in a few ways:</p> <ul> <li>I'm capturing the first parameter that jQuery passes into <code>.each</code> and using it as Unique Identifier between Audio Players</li> <li>For each audio player the <code>&lt;audio&gt;</code> element, and it's <code>playing</code> state are being kept in the local Object <code>Audio</code></li> <li>I store a reference to each <code>Audio</code> Object as an array element in the global array <code>Audios</code>; using the unique identifier as the index</li> <li><code>lastPlay</code> now only holds the unique identifier of the last played audio element; I use it to access the appropriate Object in the <code>Audios</code> array, and set the relavent <code>playing</code> when necessary.</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload