I have read over many people's similar questions and have not found an answer. So I'm asking my own question.
I have been building a feature that allows my users to play all audio tracks on the page they're viewing. However, to make my audio player initially appear on the page, I have to initPlayer()
at least once when a user clicks the Play All button.
The problem is, I am using a for loop to iterate over all of the song id's in an array to fill the playlist with songs.
var theids = ids.split(",");
for (var i = 0; i < theids.length; i++) {
getItem(theids[i], type).done(function(obj) {
if (obj.status == 'success') {
mep.mepPlaylistTracks = obj.tracks;
initPlayer();
addToPlay(obj.tracks, play);
}
});
}
initPlayer()
relies on information from my getItem()
function to properly initiate the first time. So it has to be placed in this order.
Is there a way I can fire my initPlayer()
function only once in my for
loop? It is causing my player to reinitiate each time a song is added to the playlist, which is causing performance and visual issues.
Is this sort of thing possible in Javascript?
Edit to add initPlayer()
and getItem()
functions. I am new to Javascript
, any help is appreciated.
// init player
function initPlayer(){
$('.app-player').removeClass('hide');
$('#app').removeClass('hide-player');
var playlist = $( '.playlist' ).mepPlaylist({
audioHeight: '40',
audioWidth: '100%',
videoHeight: '40',
videoWidth: '100%',
audioVolume: 'vertical',
mepPlaylistLoop: true,
alwaysShowControls: true,
mepSkin: 'mejs-audio',
mepResponsiveProgress: true,
mepAutoPlay: false,
mepSelectors: {
playlist: '.playlist',
track: '.track',
tracklist: '.tracks'
},
features: [
//'meplike',
'mepartwork',
'mepcurrentdetails',
'mepplaylist',
'mephistory',
'mepprevioustrack',
'playpause',
'mepnexttrack',
'progress',
'current',
'duration',
'volume',
'mepicons',
'meprepeat',
'mepshuffle',
'mepsource',
'mepbuffering',
'meptracklist',
'mepplaylisttoggle',
'youtube'
],
mepPlaylistTracks: mep.mepPlaylistTracks
});
function getItem(id, type){
return $.ajax({
type : "post",
dataType : "json",
url : ajax.ajax_url,
data : {action: "ajax_music", id: id, type: type, nonce: ajax.nonce}
});
}