Horacije Horacije -3 years ago 119
Javascript Question

Toggle play/pause button (Multiple audios)

I have multiple audios on my page, each with play/pause button.

<?php if ( have_posts() ) : ?>

<?php

// the query
$predigten_all_query = new WP_Query(array(
'post_type'=>'predigten',
'post_status'=>'publish',
'posts_per_page'=>-1)); ?>

<?php if ( $predigten_all_query->have_posts() ) : ?>

<div class="content-box">
<!-- the loop -->
<?php while ( $predigten_all_query->have_posts() ) : $predigten_all_query->the_post(); ?>

<?php
// vars
$mp3 = get_field('mp3');
$mp3_url = $mp3['url'];
?>
<div class="archive-content">
<div class="play-wrap">
<audio src="<?php echo $mp3_url; ?>" id="music"></audio>
<i class="fa fa-play" id="play"></i>
</div>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3><br>
<a href="<?php echo $mp3_url; ?>" class="mp3-btn" download>
<i class="fa fa-share-square-o"></i>
</a>
</div>

<?php endwhile; ?>
<!-- end of the loop -->
</div>


Here is my script that changes class of icon so it can toggle to "play" or "pause" icon.

jQuery(document).ready(function($) {
$("#play").click(function() {
var audio = document.getElementById('music');
if (audio.paused) {
audio.play();
$('#play').removeClass('fa fa-play')
$('#play').addClass('fa fa-pause')
} else {
audio.pause();
audio.currentTime = 0
$('#play').removeClass('fa fa-pause')
$('#play').addClass('fa fa-play')
}
});
});


Problem is that this works only for my first audio button. Do I need to create a dynamic IDs and if I need to do it, how to do everything right??

Thank you very much!

Answer Source

The issue is because you have multiple #play and #music elements in the DOM when they must be unique. You can solve the issue by using a class on the play button instead, then using DOM traversal in the click handler to find the related audio element. Try this:

<div class="play-wrap">
  <audio src="<?php echo $mp3_url; ?>" class="music"></audio>
  <i class="fa fa-play play"></i>
</div>
$(".play").click(function() {
  var audio = $(this).closest('.play-wrap').find('.music')[0];

  if (audio.paused) {
    audio.play();
  } else {
    audio.pause();
    audio.currentTime = 0
  }

  $(this).toggleClass('fa-play fa-pause');
});

Also note the use of toggleClass() to simplify the changing of the classes between play states.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download