Skip to content

@kressaty /ga-youtube.js
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.