Skip to content

Instantly share code, notes, and snippets.

@gabrielgilini
Created April 17, 2015 21:31
Show Gist options
  • Save gabrielgilini/c427e7a699c449068282 to your computer and use it in GitHub Desktop.
Save gabrielgilini/c427e7a699c449068282 to your computer and use it in GitHub Desktop.
Fire GA tags based on % of the YT video watched
var player = new YT.Player(container.find('iframe')[0]);
var firedPlay = false;
var progressFired = {25: false, 50: false, 75: false};
player.addEventListener('onStateChange', function (e) {
var duration = player.getDuration();
switch (e.data) {
case YT.PlayerState.PLAYING:
container.data('played', true);
if (!firedPlay) {
ga('send', 'event', 'video_play', 'video', 'alpargatas');
firedPlay = true;
}
progressTimer = window.setInterval(function () {
var progress = Math.round(player.getCurrentTime() / duration * 100);
_.each(_.keys(progressFired), function (target) {
if (Math.abs(progress - target) <= 2 && !progressFired[target]) {
ga('send', 'event', 'video_' + target, 'video', 'alpargatas');
progressFired[target] = true;
}
})
}, duration / 100 * 1000);
break;
case YT.PlayerState.PAUSED:
window.clearInterval(progressTimer);
break;
case YT.PlayerState.ENDED:
ga('send', 'event', 'video_100', 'video', 'alpargatas');
break;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment