Skip to content

Instantly share code, notes, and snippets.

@kressaty
Created September 24, 2012 18:26
Show Gist options
  • Save kressaty/3777478 to your computer and use it in GitHub Desktop.
Save kressaty/3777478 to your computer and use it in GitHub Desktop.
Track YouTube Events in Google Analytics
//NOTE: you must also include https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api?enablejsapi=1&version=3&showinfo=0";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('target_div_id', { //replace target_div_id with the id of the div the video should render in
height: '480',
width: '640',
videoId: 'XXXXX', //REPLACE THIS WITH YOUR VIDEO ID
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
_gaq.push(['_trackEvent', 'Videos', 'Play', player.getVideoUrl() ]);
}
if (event.data == YT.PlayerState.ENDED) {
_gaq.push(['_trackEvent', 'Videos', 'Completed', player.getVideoUrl() ]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment