JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://www.youtube.com/iframe_api"></script>
<div id="player"></div>
<button id="button">queue 2 more videos</button>
CSS
div {
width:300px;
height:240px;
background-color: yellow;
}
JavaScript
var player;
var playlist = ['b_XKnkQZkOM','dnNt78eGjSM'];
var previousIndex = 0;
$(window).load(function(){
player = new YT.Player('player', {
height: '240',
width: '300',
playerVars : {
playlist: playlist.join(','),
},
events: {
onStateChange: function(event) {
/*
the video has changed
seize the opportunity to update the playlist without interruption
*/
if(event.data == -1) {
// get current video index
var index = player.getPlaylistIndex();
// update when playlists do not match
if(player.getPlaylist().length != playlist.length) {
// update playlist and start playing at the proper index
player.loadPlaylist(playlist, previousIndex+1);
}
/*
keep track of the last index we got
if videos are added while the last playlist item is playing,
the next index will be zero and skip the new videos
to make sure we play the proper video, we use "last index + 1"
*/
previousIndex = index;
}
}
}
});
});
$(document).ready(function() {
$('#button').click(function(){
playlist.push('ZVeaEl7nMWM');
playlist.push('YRBwXHowb6I');
});
});