I want to loop this video list with image attached: when the last video ends the first one of the list starts, how is it possible to do it?
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
const playerElement = document.querySelector('#player');
const imageElement = document.querySelector('#slide');
const videos = {
'RGpr3Y6Q-1M': 'image1.png',
'btxdcqLOGuc': 'image2.png',
'CIx0a1vcYPc': 'image3.png',
'6-4KydP92ss': 'image4.png'
};
I want to loop this video list with image attached: when the last video ends the first one of the list starts, how is it possible to do it? This part about the custom buttons.
const videoIds = Object.keys(videos);
function onYouTubeIframeAPIReady() {
function onPlayerReady({ target }) {
var playButton = document.getElementById("play-button");
playButton.addEventListener("click", function() {
target.playVideo();
});
var pauseButton = document.getElementById("pause-button");
pauseButton.addEventListener("click", function() {
target.pauseVideo();
});
var next = document.getElementById("next");
next.addEventListener("click", function() {
target.nextVideo();
});
var pre = document.getElementById("previous");
pre.addEventListener("click", function() {
target.previousVideo();
});
target.loadPlaylist({
playlist: videoIds
});
}
function onPlayerStateChange({ data, target }) {
switch(data) {
case YT.PlayerState.ENDED:
target.nextVideo();
break;
case YT.PlayerState.BUFFERING:
const playlist = target.getPlaylist();
const playlistIndex = target.getPlaylistIndex();
const currentId = playlist[playlistIndex];
const image = videos[currentId];
if (imageElement.src !== image) {
imageElement.src = image;
}
break;
}
}
and this my YT player
const player = new YT.Player(playerElement, {
height: '405',
width: '720',
playerVars: {
controls: 1,
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
You may try this. We are starting by creating array of objects first. Then we need to iterate and restrict iterator according to length of our array.
const videos = [
{id : 'RGpr3Y6Q-1M', img : 'image1.png'},
{id : 'btxdcqLOGuc', img : 'mage2.png'},
{id: 'CIx0a1vcYPc' , img : 'mage3.png'},
{id : '6-4KydP92ss' , img : 'mage4.png'}
];
var num =-1 ;
pickTheVideo =( )=>{
num = num + 1
if( num > videos.length -1 ){ num =-1 ; return ( pickTheVideo( ) ) }
return videos[ num ]
}
for (let index = 0; index < 10 ; index++) {
const videoObj = pickTheVideo() ;
console.log( index , "videoObj" , videoObj )
}