Skip to content

Instantly share code, notes, and snippets.

@aradnom
Created July 22, 2013 17:57
Show Gist options
  • Save aradnom/6056023 to your computer and use it in GitHub Desktop.
Save aradnom/6056023 to your computer and use it in GitHub Desktop.
Simple script for embedding multiple youtube videos via the JS API. Allows video objects to be queued as video params along with a callback on state change (useful for pushing tracking events).
var videos = [],
tag = document.createElement( 'script' );
// Load the API
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName( 'script' )[0];
firstScriptTag.parentNode.insertBefore( tag, firstScriptTag );
// Enqueue new youtube video for loading and event tracking
// video params:
// video_id: video ID
// element: parent HTML tag
// width
// height
// callback: function to execute on state change, takes the event as an argument
function enqueueYoutubeVideo( video ) {
videos.push( video );
}
// Embed the videos
function onYouTubeIframeAPIReady () {
// Load each video in the queue
for ( video in videos ) {
var videoPlayer = new YT.Player( videos[video].element, {
width: videos[video].width ? videos[video].width : '780',
height: videos[video].height ? videos[video].height : '465',
videoId: videos[video].video_id,
playerVars: {
showinfo: 0,
wmode: 'transparent'
},
events: {
'onStateChange': onStateChange
}
});
}
}
function onStateChange ( event ) {
for ( video in videos ) {
videos[video].callback( event );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment