This Javascript class will simplify the embedding and event tracking of YouTube videos on your website. It utilizes and requires the jQuery library (for better implementation), Google Analytics library (for event tracking) and swfobject (for YouTube embedding). So the basic Javascript implementation will be something like:
<script>
$(function() {
var ytplayer = new YouTubePlayer('lNdljbYy0qk', 'ytplayer', '560', '340');
ytplayer.embed();
});
</script>
Where ‘lNdljbYy0qk’ is the YouTube Video ID, ‘youtube_player’ is the HTML element ID where you want to embed your video, ’560′ and ’340′ are the width and the height respectively.
Below is the code of the class itself:
var YT_ATT_ID;
(function($) {
YouTubePlayer = function(vid, id, w, h, params, atts) {
this.vid = vid;
this.id = id;
this.width = w;
this.height = h;
this.playerApiId = id + '_apiid';
//the global variable, i should find a better way to pass the value
YT_ATT_ID = id + '_attid';
var defaultParams = {
allowScriptAccess: "always", allowFullScreen: "true", allowScriptAccess: "always", wmode: "opaque"
};
var defaultAtts = {
id: YT_ATT_ID
};
this.params = $.extend(defaultParams, params);
this.atts = $.extend(defaultAtts, atts);
}
var yto = YouTubePlayer.prototype;
yto.embed = function() {
// we need swfobject
try {
swfobject.embedSWF('http://www.youtube.com/v/' + this.vid + '?fs=1&hl=en_US&enablejsapi=1&playerapiid=' + this.playerApiId,
this.id, this.width, this.height, "8", null, null, this.params, this.atts);
}catch(e) {
var txt = "javascript error";
txt += "error description: " + err.description + "\n\n";
txt += "click OK to continue.\n\n";
alert(txt);
}
}
YouTubeTracker = {
player: {
state: {
'-1': 'unstarted',
'0': 'ended',
'1': 'playing',
'2': 'paused',
'3': 'buffering',
'5': 'cued'
},
obj: null,
events: [],
elapsedTime: 0, //the longest elapsed time
hasEnded: false
},
init: function(player) {
this.player.obj = player;
player.addEventListener('onStateChange', 'onPlayerStateChange');
},
track: function(stateNum) {
this.getTimeInTens(this.player.elapsedTime);
switch(this.player.state[stateNum]) {
case 'playing':
// get the longest elapsed time
this.player.elapsedTime = (this.player.obj.getCurrentTime() > this.player.elapsedTime) ? this.player.obj.getCurrentTime() : this.player.elapsedTime;
if(-1 == $.inArray(this.player.state[stateNum], this.player.events))
this.player.events.push(this.player.state[stateNum]);
break;
case 'paused': // we don't really care about pause at this time.
// get the longest elapsed time
this.player.elapsedTime = (this.player.obj.getCurrentTime() > this.player.elapsedTime) ? this.player.obj.getCurrentTime() : this.player.elapsedTime;
break;
case 'cued':
this.player.events.push(this.player.state[stateNum]);
break;
case 'ended':
//this.player.events.push(this.player.state[stateNum]);
this.player.hasEnded = true;
break;
}
},
getTimeInTens: function(elapsedTime) {
var res = elapsedTime / 10;
var estimatedTime = Math.ceil(res) * 10;
return estimatedTime;
},
constructAction: function() {
var action = location.pathname.replace(/\/+$/,"");
this.player.events.push(this.getTimeInTens(this.player.elapsedTime));
action += '#' + this.player.events.join(',');
return action += this.player.hasEnded == true ? ',ended' : '';
}
}
})(jQuery)
// track the number of seconds, get the longest time
$(window).bind('unload', function(){
// don't forget your GA library
var action = YouTubeTracker.constructAction();
try {
// at this point be sure that you have your analytics code embedded
pageTracker._trackEvent(YT_ATT_ID, action, 'YT_elapsedTime10secInterval');
}catch(e) {
//put something here
}
});
// youtube api's primitive functions
function onYouTubePlayerReady(playerId) {
ytplayer = document.getElementById(YT_ATT_ID);
YouTubeTracker.init(ytplayer);
}
function onPlayerStateChange(state) {
YouTubeTracker.track(state);
}
There are a lot of things we can do to improve this class. But this works well for me so far.
Please don’t forget to reference your jquery, swfobject, and google analytics code. Enjoy!












