Skip to content

Instantly share code, notes, and snippets.

@jacobovidal
Last active December 30, 2018 07:42
Show Gist options
  • Save jacobovidal/74bf75a1d6cc037007e07c6690de7e49 to your computer and use it in GitHub Desktop.
Save jacobovidal/74bf75a1d6cc037007e07c6690de7e49 to your computer and use it in GitHub Desktop.
Google Analytics scroll tracking snippet using dataLayer
// https://github.com/felix/gtm-scrolldepth
var startTime = +new Date;
var scrollCache = [];
documentElement = document.documentElement;
function throttle(func, wait) {
var context, args, result;
var timeout = null;
var previous = 0;
var later = function () {
previous = new Date;
timeout = null;
result = func.apply(context, args);
};
return function () {
var now = new Date;
if (!previous) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
}
function calculateMarks(docHeight) {
return {
'20%': parseInt(docHeight * 0.20, 10),
'40%': parseInt(docHeight * 0.50, 10),
'60%': parseInt(docHeight * 0.60, 10),
'80%': parseInt(docHeight * 0.80, 10),
'100%': docHeight - 5
};
}
function checkMarks(marks, scrollDistance, timing) {
// Check each active mark
for (key in marks) {
if (scrollCache.indexOf(key) === -1 && scrollDistance >= marks[key]) {
dataLayer.push({
'event': 'scrollDepth',
'eventCategory': 'Scroll Depth',
'eventAction': 'Percentage',
'eventLabel': key,
'eventTiming': timing,
})
scrollCache.push(key);
sendEvent('Percentage', key, scrollDistance, timing);
}
}
}
function rounded(scrollDistance) {
// Returns String
return (Math.floor(scrollDistance / 250) * 250).toString();
}
function getDocumentHeight() {
return Math.max(
document.body.scrollHeight || 0, documentElement.scrollHeight || 0,
document.body.offsetHeight || 0, documentElement.offsetHeight || 0,
document.body.clientHeight || 0, documentElement.clientHeight || 0
);
}
function getScrollDistance() {
return window.pageYOffset || document.body.scrollTop ||
documentElement.scrollTop || 0;
}
function getWindowHeight() {
return window.innerHeight || documentElement.clientHeight ||
document.body.clientHeight || 0;
}
window.onscroll = throttle(function () {
var docHeight = getDocumentHeight(),
winHeight = getWindowHeight(),
scrollDistance = getScrollDistance() + winHeight,
// Recalculate percentage marks
marks = calculateMarks(docHeight),
// Timing
timing = +new Date - startTime;
// If all marks already hit, unbind scroll event
if (scrollCache.length >= 5) {
//$window.off('scroll.scrollDepth');
return;
}
checkMarks(marks, scrollDistance, timing);
}, 500);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment