Skip to content

Instantly share code, notes, and snippets.

@abrjagad
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abrjagad/9c9d26ef613eaa6fe44a to your computer and use it in GitHub Desktop.
Save abrjagad/9c9d26ef613eaa6fe44a to your computer and use it in GitHub Desktop.
var player, playButton = document.getElementById("play-button"),youttubeplayer = [];
/* this function gets called when API is ready to use*/
function onYouTubePlayerAPIReady() {
/* create the global player from the specific iframe (#video)*/
if (typeof(youtubeVideo) !== "undefined") {
player = new YT.Player('video', {
videoId: youtubeVideo,
playerVars: {
wmode: "opaque"
},
events: {
/* call this function when player is ready to use*/
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
/*when the youtube is embedded as iframe*/
$(function() {
try {
$(".videourl").each(function(i, v) {
var id = 'videourl' + i;
youttubeplayer[i] = new YT.Player(id);
});
} catch (e) {
}
});
}
function onPlayerReady(event) {
/* bind events*/
playButton.addEventListener("click", function() {
player.playVideo();
});
}
/* when video ends*/
function onPlayerStateChange(event) {
if (event.data === 0) {
//do something
}
}
/* Inject YouTube API script*/
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
/*youtube ends*/
//when the video is embedded as iframe
//please check the iframe src
//it should have "enablejsapi=1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment