Skip to content

Instantly share code, notes, and snippets.

@GirlBossRush
Forked from larsmqller/mr-file.js
Last active September 6, 2018 22:59
Show Gist options
  • Save GirlBossRush/595ad370add5c348ca58680a3cd42e9e to your computer and use it in GitHub Desktop.
Save GirlBossRush/595ad370add5c348ca58680a3cd42e9e to your computer and use it in GitHub Desktop.
function sendTrackEvent (eventData) {
window.ga('send', Object.assign({hitType: 'event'}, eventData);
}
function trackVideoEvents (videoElement) {
var $videoElement = $(videoElement);
var markers = [.1, .2, .3, .4, .5, .6, .7, .8, .9, 1];
var gaLoggingName = this.dataset.gaLoggingName;
var isTrackingProgress = false
function checkVideoProgress () {
var currentMarker = markers[0];
if (isTrackingProgress && videoElement.duration && currentMarker) {
var progress = videoElement.currentTime / videoElement.duration;
if (progress >= currentMarker) {
markers.shift(); // Remove first
// calc mark to percentage
var fixedMarker = parseFloat((currentMarker * 100).toFixed());
fixedMarker = fixedMarker + '%';
if (isTrackingProgress > 1) {
fixedMarker = 'complete';
}
sendTrackEvent({
hitType: 'event',
eventCategory: 'Video',
eventAction: fixedMarker,
eventLabel: gaEventLabel
});
// console.log(fixedMarker);
}
isTrackingProgress = progress < 1; // Are we finished?
window.requestAnimationFrame(checkVideoProgress);
}
}
function initProgressTracking () {
isTracking = true
checkVideoProgress()
}
$videoElement.on('play', function () {
sendTrackEvent({
eventCategory: 'Video',
eventAction: 'Start',
eventLabel: gaLoggingName
})
})
if (typeof videoElement.duration === 'number' && videoElement.duration > 0) {
initProgressTracking()
} else {
$videoElement.once('durationchange', initProgressTracking)
}
}
fl.videoLog = {
init: function () {
$('video[data-ga-logging-name]').each(trackVideoEvents)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment