GC Youtube Player iFrame API on Click or Delay
GC Youtube Player iFrame API on Click or Delay
by zachreynolds
HTML
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<button type="button" id="createPlayer">Create Youtube Player</button>
<button type="button" id="destroyPlayer">Destroy Youtube Player</button>
<br>
<br>
<div id="video-container">
<div id="player"></div>
</div>
<br>
<button type="button" class="yt-play" id="yt-play">Youtube Play</button>
<button type="button" class="yt-pause" id="yt-pause">Youtube Pause</button>
<button type="button" class="yt-new" id="yt-new">New Youtube</button>
JavaScript
var videoIDs = Array('vSW2M-BB1NE', 'o5FzCz8NC58', 'nfs8NYg7yQM', '987xHnVfRI4', 'dT2owtxkU8k', 'jn40gqhxoSY');
// 2. This code loads the IFrame Player API code asynchronously.
var yPlayer;
/*
setTimeout(function(){
loadYouTubeApi();
}, 2000);
*/
function loadYouTubeApi() {
/*
if (typeof tag === "undefined") {
// if first run load the YT API which will call the correct functions.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
} else {
// if YT api already loaded, we need to call the function.
onYouTubeIframeAPIReady();
}
*/
// old code
//$("#video-container").html('<div id="player"></div>');
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
videoID = videoIDs[Math.floor(Math.random() * videoIDs.length)];
}
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
//var player;
function onYouTubeIframeAPIReady() {
yPlayer = new YT.Player('player', {
height: '390',
width: '640',
//videoId: 'M7lc1UVf-VE',
videoId: videoID,
events: {
'onReady': onPlayerReady
}
});
}
// This function plays video without sound,
// once the player is ready.
/*
function playVideo() {
yPlayer.playVideo();
yPlayer.mute();
}
*/
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
yPlayer.setPlaybackRate(1);
//event.target.playVideo();
yPlayer.playVideo();
//yPlayer.mute();
}
/* GC CREATE DESTROY PLAYER */
$("#createPlayer").on("click", function() {
loadYouTubeApi();
});
$("#destroyPlayer").on("click", function() {
yPlayer.destroy();
$(".yt-play,...