I am required to initialize list of Youtube iframe video
because there is many youtube video and the list are changeable from admin site I am required to make it dynamic, which is using class instead of id
this is the current code
const players = [];
onYouTubeIframeAPIReady(0);
onYouTubeIframeAPIReady(1);
function onYouTubeIframeAPIReady(index) {
players[index] = new YT.Player($('.wow_youtube_video')[index], {
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
// play
if(event.data == 1){
action = 'play';
}
// pause
if(event.data == 2){
action = 'pause';
}
if(event.data == 1 || event.data == 2){
dataLayer.push({
'event': 'trackEvent',
'eventDetails.category': 'videos',
'eventDetails.action': action,
'eventDetails.label': players[0].getVideoData().title // players[0] supposedly be players[index] but don't know how to pass the index balue from above function to this function
'videoName': players[0].getVideoData().title, //video name
'videoType': 'video on demand' //video type
});
}
}
as you can see above, the 8th line from the bottom
'eventDetails.label': players[0].getVideoData().title,
this code here the
players[0]
supposedly be players[index]
but I don't know how to pass the index value from
players[index] = new YT.Player($('.wow_youtube_video')[index], {
events: {
'onStateChange': onPlayerStateChange
}
});
to the onPlayerStateChange
function
the purpose of this is to be able to carry the index value so that the code can be dynamic, thus I only need to put class name wow_youtube_video on any youtube iframe to make it works
Any help is appreciated, thank you
on function onYouTubeIframeAPIReady
add this
players[index] = new YT.Player($('.wow_youtube_video')[index], {
events: {
'onStateChange': onPlayerStateChange.bind(index)
}
});
now you can get index
in onPlayerStateChange
by
function onPlayerStateChange(event) {
let index = this;
console.log(index);
}