Skip to content

Instantly share code, notes, and snippets.

@tjFogarty
Created April 30, 2013 14:38
Show Gist options
  • Save tjFogarty/5489153 to your computer and use it in GitHub Desktop.
Save tjFogarty/5489153 to your computer and use it in GitHub Desktop.
Tracking for any number of YouTube iframes. Uses a data-title attribute for grabbing a title.
// Any iframes with a class of .yt will be collected for event tracking
var Youtube = {
$players: $( '.yt' ),
playerArray: [],
numPlayers: $( '.yt' ).length - 1,
init: function() {
Youtube.assignID();
Youtube.bindEvents();
},
// Give all videos a unique ID - video-0, video-1 etc...
assignID: function() {
var i = Youtube.numPlayers;
for ( i ; i >= 0; i--) {
$( Youtube.$players[i] ).attr( 'id', 'video-' + i );
}
},
// For every video ID (which we set with assignID())
// we will create a new 'YT.Player' and store within our playerArray []
bindEvents: function() {
var i = Youtube.numPlayers,
videoID = null,
$video = null;
for ( i ; i >= 0; i--) {
videoID = $(Youtube.$players[i]).attr('id');
Youtube.playerArray[i] = new YT.Player( videoID , {
events: {
'onStateChange': function( e ) {
if( e.data == YT.PlayerState.PLAYING ) {
$video = $( e.target.a );
_gaq.push( ['_trackEvent', 'YouTube Video', 'play', $video.data('title') ]);
}
}
}
});
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment