javascript - How to have multiple instances of one jQuery player object in a page (Audio object) -
i have made customised audio player, problem can have 1 player in each html page. because since js code associated example class .play
then if there 2 .play
classes on page, both work. while 1 pressed supposed work. here simplified version of player. know example can solved using this
in part of code, imagine full plugin 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 can see, if press button play, both icons works, while 1 pressed supposed work. looking proper solution having various instances of same plugin in single page.
there similar question title, point of question considering audio object page can play 1 of them, no matter if there 1 instance of player of multiple.
pass "target" css , push each instance array can call methods on them using index position. controls apply instance 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);
Comments
Post a Comment