Given that you're repeating the same pair of elements throughout the DOM it would make more sense to make the code generic. To do that use DOM traversal to get the previous sibling audio
element to the clicked a
element. To do that you can use the previousSibling
from the reference to the clicked element:
function togglePlay(el) {
var audio = this.previousSibling;
return audio.paused ? audio.play() : audio.pause();
};
<audio id="myfile" src="/musicfile/{{$ebeat->beat}}" preload="auto"></audio>
<a onClick="togglePlay(this)">{{$ebeat->title}}</a>
Alternatively, as you tagged the question with jQuery, you can use prev()
, like this:
$(function() {
$('a.togglePlay').click(function(e) {
var audio = $(this).prev()[0];
return audio.paused ? audio.play() : audio.pause();
});
});
<audio id="myfile" src="/musicfile/{{$ebeat->beat}}" preload="auto"></audio>
<a href="#" class="togglePlay">{{$ebeat->title}}</a>