mrSidX
mrSidX

Reputation: 357

Dynamically accessing getElementId when iterating {{#each id}}

I have a get response returning an array of url pointing to audio recorded voicemails and I want to play on my voicemail front ui in handlebars with the pretty play button and show the pause when playing and vice versa,

My problem is when I try to style the play button, I need to access by element id to change animation, but each time the the {{#each}} iterates to next objects, it duplicates their element id, and when I apply this script to try and style a pause button, I of course get issues.

<script>
  function play() {
    var audio = document.getElementById('audio');
    if (audio.paused) {
      audio.play();
      $('#play').removeClass('fa-play-circle')
      $('#play').addClass('fa-pause-circle')
    }else{
      audio.pause();
      audio.currentTime = 0
      $('#play').addClass('fa-play-circle')
      $('#play').removeClass('fa-pause-circle')
    }
  }
</script>;

whats the best means of tackling this issue?

Heres the code:

 {{#each vm}}
    {{#each this}}

      <div class="container text-light bg-dark" style="border-width:3; border-style:solid; border-color:black; margin-bottom:5px;">

         <div class="bglight">
             Date: {{datecreated}} / Duration: {{RecordingDuration}} / From: {{From}} / 

            <audio src="{{RecordingUrl}}" id="audio"></audio>
            <i class="far fa-play-circle" id="play" onclick='play()'></i>

       </div>
  </div>
     {{/each}}
 {{/each}}

Upvotes: 0

Views: 34

Answers (1)

mplungjan
mplungjan

Reputation: 178350

IDs need to be UNIQUE. Use a class and unobtrusive coding:

$(".play").on("click",function() {
  var audio = $(this).prev();
  if (audio.paused) { ... } 

});

Upvotes: 1

Related Questions