Madamadam
Madamadam

Reputation: 938

Adding play buttons for all audio tags on a page

I want to add a play button for each audio file on a page. Therefore I added a button with an indexed classname under each audio-tag, but now I don't know how to proceed and bind the click event to the buttons. Maybe there's a much more elegant approach in general …

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<audio id="myaudio" src="http://www.soundjay.com//mechanical/gun-cocking-01.mp3">
</audio>

<audio id="myaudio" src="http://www.soundjay.com//mechanical/gun-cocking-02.mp3">
</audio>
$( "audio" ).each(function( index ) {
   $( '<button class=audioButton"' + index + '">Play Clip #' + index + '</button>' ).insertAfter( this );
});

$("button").on("click", playTest);

Upvotes: 2

Views: 130

Answers (2)

Rachel Gallen
Rachel Gallen

Reputation: 28553

I noticed you were using multiple ids of the same value (never going to work), so i removed them. I used the previous posters code to create the buttons, but have elaborated to show how you can call each audio in the playTest function. Hope this helps!

$("audio").each(function(index) {
  $(this).attr('id','myaudio' + index);
  $('<button id="audio' + index + '">Play Clip #' + index + '</button>').insertAfter(this);
});

$("body").on("click", "button", playTest);

function playTest() {
  var audid = 'my'+ $(this).attr('id');
  playAudio(audid);
}

function playAudio(str) {
  var currAudio = document.getElementById(str);
  if (currAudio.paused) {
    currAudio.play();
  } else {
    currAudio.pause();
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<audio src="http://www.soundjay.com//mechanical/gun-cocking-01.mp3">
</audio>

<audio src="http://www.rachelgallen.com/monkey.mp3">
</audio>

Upvotes: 1

brk
brk

Reputation: 50291

SInce the buttons are dynamically created you have to delegate the any event that you want to execute on it.

Hope this snippet will be useful

$( "audio" ).each(function( index ) {
   $( '<button class="audioButton' + index + '">Play Clip #' + index + '</button>' ).insertAfter(this );
});

$("body").on("click","button" ,playTest);
function playTest(){
 alert($(this).prop('class'))

}

JSFIDDLE

Upvotes: 1

Related Questions