Skip to content

Instantly share code, notes, and snippets.

@zolitch
Last active August 29, 2015 14:11
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 zolitch/2c3c99ba5fe2780c32b6 to your computer and use it in GitHub Desktop.
Save zolitch/2c3c99ba5fe2780c32b6 to your computer and use it in GitHub Desktop.
Videoplayer require js module to leverage Youtube api
/*
Videoplayer
Author: Stephen Zsolnai (http://www.zolla.co.uk)
Decription: Youtube api video module.
This module will wait for the global callback from Youtube API if it is requested.
That is the trigger to set up the necessary video players.
Events will be fired to send tracking data and the video data is pulled from embedded iframes like so:
<iframe id="competitionVideo"
class="js-player"
data-id="9wsnelEA3ME"
data-title="The title of the video"
type="text/html"
width="640"
height="390"
data-trigger-link="watchVideo"
src="http://www.youtube.com/embed/9wsnelEA3ME?enablejsapi=1"
frameborder="0"></iframe>
--------------------------------------------------------------------------*/
define([
'jquery',
'modules/gatracking'
], function ($, tracking) {
'use strict';
var videoPlayers = [];
//video player instance.
var Player = function($target) {
this.player = new YT.Player($target[0], {
events: {
'onReady': onPlayerReady.bind(this),
'onStateChange': onPlayerStateChange.bind(this)
}
});
this.title = $target.data('title');
this.id = $target.data('id');
this.$triggerLink = $('#' + $target.data('triggerLink'));
//Play related youtube video on trigger click.
if (this.$triggerLink.length) {
this.$triggerLink.on('click', function(e) {
e.preventDefault();
this.player.playVideo();
}.bind(this));
}
}
var onPlayerReady = function() {
//nothing needs doing here as yet...
},
onPlayerStateChange = function(event) {
if (event.data === YT.PlayerState.PLAYING) {
tracking.sendEvent('video', 'play', this.title + '(' + this.id + ')');
}
if (event.data === YT.PlayerState.PAUSED) {
tracking.sendEvent('video', 'pause', this.title);
}
}
;
//Global entry point for API
window.onYouTubeIframeAPIReady = function() {
var $player = $('.js-player');
if ($player.length) {
$player.each(function() {
videoPlayers.push(new Player($(this)));
});
}
}
var VideoPlayer = {
activate: function() {
//Load in the youtube api if a player exists on the page.
//Thje rest of the module is initialised on the Youtube api callback once it has loaded.
var $player = $('.js-player');
if ($player.length) {
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
}
};
return VideoPlayer;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment