Created
July 22, 2013 17:57
-
-
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).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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