Last active
August 29, 2015 14:10
-
-
Save Godoy/1c8181c74947c539d9e4 to your computer and use it in GitHub Desktop.
Track Google Analytics video Youtube
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div id="player-id"></div> | |
<script> | |
//Load iframe api | |
var tag = document.createElement('script'); | |
tag.src = "http://www.youtube.com/iframe_api"; | |
var firstScriptTag = document.getElementsByTagName('script')[0]; | |
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); | |
var pauseFlag = false; | |
function onPlayerReady(event) { | |
// do nothing, no tracking needed | |
} | |
function onPlayerStateChange(event) { | |
// track when user clicks to Play | |
if (event.data == YT.PlayerState.PLAYING) { | |
ga('send', 'event', 'Video', 'Play'); | |
pauseFlag = true; | |
} | |
// track when user clicks to Pause | |
if (event.data == YT.PlayerState.PAUSED && pauseFlag) { | |
ga('send', 'event', 'Video', 'Pause'); | |
pauseFlag = false; | |
} | |
// track when video ends | |
if (event.data == YT.PlayerState.ENDED) { | |
ga('send', 'event', 'Video', 'End'); | |
} | |
} | |
//This code is called by the YouTube API to create the player object | |
function onYouTubeIframeAPIReady(event) { | |
player = new YT.Player('player-id', { | |
videoId: 'mIzfV4AO8gQ', | |
events: { | |
'onReady': onPlayerReady, | |
'onStateChange': onPlayerStateChange | |
} | |
}); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment