Skip to content

Instantly share code, notes, and snippets.

@TrevorJTClarke
Created May 5, 2015 22:14
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 TrevorJTClarke/41788ad8bc178aad3aeb to your computer and use it in GitHub Desktop.
Save TrevorJTClarke/41788ad8bc178aad3aeb to your computer and use it in GitHub Desktop.
A quick youtube API adapter for playing nicely with other javascript modules.
/**
* Youtube quick module
*
* USE:
* var _yt = new youtube().init({
* element: "player",
* height: 350,
* width: 640,
* videoId: 'M7lc1UVf-VE'
* });
*
* _yt is the instance for handling/controlling events and player
*/
function youtube (){
this.options = {};
this.scriptLoaded = false;
this.init = function ( options ) {
this.options = options || {};
if(!this.options.element){throw new Error("Must specify youtube element!");}
if(!this.options.videoId){throw new Error("Must specify youtube video Id!");}
var _self = this;
// load the video element and logic
_self.loadVideo();
// load in the script
if(_self.scriptLoaded !== true){
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
_self.scriptLoaded = true;
}
return this;
};
this.loadVideo = function() {
var _self = this;
var player;
window.onYouTubeIframeAPIReady = function () {
_self.playerInstance = new YT.Player(_self.options.element, {
height: _self.options.height || '390',
width: _self.options.width || '640',
videoId: _self.options.videoId,
playerVars: { 'autoplay': 1 }, // needed so we have access to the methods right away
events: {
'onReady': _self.onReady,
'onStateChange': _self.onStateChange
}
});
};
};
this.onReady = function(event) {
// Loads up the video methods within _self.playerInstance
// Stops the autoplay from moving forward
event.target.pauseVideo();
event.target.stopVideo();
};
this.onStateChange = function(event) {
var _self = this;
var done = false;
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(_self.stop, 6000);
done = true;
}
};
this.play = function() {
this.playerInstance.playVideo();
};
this.pause = function() {
this.playerInstance.pauseVideo();
};
this.stop = function() {
this.playerInstance.stopVideo();
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment