Skip to content
Advertisement

multi buttons on one javascript function

foreach fetch songs from database each audio have button to pause and play all buttons of all songs works with first song only… when i press button of second or third song the first run … any solution ?

blade.php

    @foreach($songs as $song)
    <audio  class="player" id="player"  src="{{asset('audios/'.$song->song)}}" type="audio/ogg" > 
   </audio>
        <div class="player-control">
            <button id="{{$song->id}}" class="playerbutton play btn btn-outline-info" 
    onclick="playmusic(this)" ><i class="fas fa-play"></i></button>
    <button id="pause" class="playerbutton pause btn btn-outline-info" 
    onclick="pausemusic(this)"><i class="fas fa-pause"></i></button>
        </div>
        @endforeach

js.file

var player=document.getElementById("player");
  function playmusic()
  {
    
    player.play();

  }
  function pausemusic(elem)
  {
    player.pause();
    
  }

Advertisement

Answer

With var player=document.getElementById("player"); you select only one audio element. If you add a unique song id to the buttons and audio tag like this:

@foreach($songs as $song)
<audio  class="player" id="player-{{$song->id}}" ... </audio>
<div class="player-control">
    <button data-song-id="{{$song->id}}" ... onclick="playmusic(this)" >...</button>
    <button data-song-id="{{$song->id}}" ... onclick="pausemusic(this)">...</button>
</div>
@endforeach

Then you may select a bound audio element directly inside the function:

  function playmusic(e)
  {
    var songId = e.dataset.songId,
     player = document.getElementById("player-" + songId);
     player.play();
  }
  function pausemusic(e)
  {
    var songId = e.dataset.songId,
     player = document.getElementById("player-" + songId);
    player.pause();
  }
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement