<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');
});
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.