Emese Pócsik Emese Pócsik - 5 months ago 33
jQuery Question

jquery multiply audio button stop siblings playing

I have 4 audio buttons. I'd like to stop the other 3 when I click on one of them. I tried with siblings function but I think it can't find the other audio. How can I stop the other audio playing?

$(document).ready(function() {
var playing = false;

$('.audio-button').click(function() {
var audio = $(this).find('audio')[0];

if (playing !== true) {
audio.play();
} else {
audio.pause();
}

$(this).toggleClass('playing');
playing = !playing;
$(this).siblings().find('audio').stop();

});
});

Answer

The problem was that you were calling the "stop()" function on the jquery elements. I just iterated through the audio elements in order to stop them. To simulate a stop, you need to invoke the pause method and set the currentTime to 0. By the way, the rest of your js script looks just fine =)

Please, check this code snippet below:

var playing = false;

$('.audio-button').click(function() {
  var audio = $(this).find('audio')[0]; 

  if (playing !== true) {
    audio.play();
  } else {
    audio.pause();
  }

  $(this).toggleClass('playing');
  playing = !playing;
  $(this).siblings().find('audio').each(function(index, elem){

    elem.pause();
    elem.currentTime = 0;

  });

});
.audio-button{
  width: 150px;
  height: 150px;
  background: orange;
  text-align: center;
  margin: 10px;
}
<div class="audio-button">
  Click here
  <audio src="http://www.nasa.gov/mp3/741263main_Bob.mp3">
  </audio>
</div> 
<div class="audio-button">
  Click here
  <audio src="http://www.nasa.gov/mp3/741261main_Charlie.mp3">
  </audio>
</div> 
<div class="audio-button">
  Click here
  <audio src="http://www.nasa.gov/mp3/741262main_Lori.mp3">
  </audio>
</div>
  <div class="audio-button">
  Click here
	 <audio src="http://www.nasa.gov/mp3/739272main_Cut%201.mp3">
	 </audio>
 </div> 


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>