Reputation: 477
I have made a customised audio player, but the problem is that I can only have one player in each HTML page. Because so since the js code is associated to for example class .play
then if there are 2 .play
classes on the page, both work. While the only one that is pressed is supposed to work. Here is a very simplified version of the player. I know this example can be solved by using this
in some part of the code, but imagine it is a full plugin with lots of functionalities.
(function($) {
var audio, src;
src = $(".player").attr("data-src");
audio = new Audio();
audio.src = src;
$(".play").on("click", function() {
if (audio.paused) {
audio.play();
$(".play").css("background", "url(https://goo.gl/w4q23U) no-repeat");
} else {
audio.pause();
$(".play").css("background", "url(https://goo.gl/xOkUZm) no-repeat");
}
});
})(jQuery);
div.player{
width:200px;
height:50px;
border:dashed 1px black;
margin:5px;
}
div.player > .play {
width: 48px;
height: 48px;
background: url(https://goo.gl/xOkUZm) no-repeat;
float:left;
}
div.player > .title{
line-height:50px;
margin-left:60px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="player" data-src="https://goo.gl/aBJE48">
<div class="play"></div>
<div class="title">track 1</div>
</div>
<div class="player" data-src="https://goo.gl/4arvDT">
<div class="play"></div>
<div class="title">track 2</div>
</div>
As you can see, if you press button to play, both icons works, while only the one that is pressed is supposed to work. I am looking for a proper solution for having various instances of the same plugin in a single page.
There are similar question with this title, but the point of this question is considering the audio object which the page can only play one of them, no matter if there is one instance of the player of multiple.
Upvotes: 0
Views: 117
Reputation: 3478
Pass a "target" for your CSS and also push each instance into an array so you can call methods on them using index position. Then the controls will apply to the instance you have selected.
(function($) {
var player = [];
var audio, src;
src = $(".player").attr("data-src");
audio = new Audio();
audio.src = src;
player.push(audio);
$(".play").on("click", function(target) {
$.each( player, function( key, value ) {
if (audio[key].paused() {
audio[key].play();
$(target).css("background", "url(https://goo.gl/w4q23U) no-repeat");
} else {
audio[key].pause();
$(target).css("background", "url(https://goo.gl/xOkUZm) no-repeat");
}
});
});
})(jQuery);
Upvotes: 1