Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
GA custom event trigger which tracks reading behavior
<script>
try {
document.addEventListener("DOMContentLoaded", function() {
var accumScrollMove = 0;
// Set it 1 msecs to avoid div by zero error
var accumScrollTime = 1;
var latestScrollTop = 0;
var latestScrollAt = new Date();
function checkScroll() {
// 1. Check scrollbar movement speed
var scrollTop = document.body.scrollTop;
var scrollAt = new Date();
var scrollTopDelta = Math.abs(latestScrollTop - scrollTop);
var scrollTimeDelta = Math.min(scrollAt - latestScrollAt, 5 * 60 * 1000); // limit max time-delta to 5 minutes
if(scrollTopDelta !== 0) {
latestScrollTop = scrollTop;
latestScrollAt = scrollAt;
accumScrollMove += scrollTopDelta;
accumScrollTime += scrollTimeDelta;
}
// 2. Check event firing condition
if(accumScrollTime > 30 * 1000 && scrollTop / document.body.scrollHeight > 0.8) {
var pixelPerSec = Math.floor(accumScrollMove / accumScrollTime * 1000);
var label = pixelPerSec > 100 ? 'skimmer' : 'reader';
ga('send', 'event', 'read', 'pps', label, pixelPerSec);
} else {
window.setTimeout(checkScroll, 500);
}
}
checkScroll();
});
} catch(e) {}
</script>
<script>
try {
(function() {
var accumScrollMove = 0;
// Set it 1 msecs to avoid div by zero error
var accumScrollTime = 1;
var latestScrollTop = 0;
var latestScrollAt = new Date();
function checkScroll() {
// 1. Check scrollbar movement speed
var scrollTop = document.body.scrollTop;
var scrollAt = new Date();
var scrollTopDelta = Math.abs(latestScrollTop - scrollTop);
var scrollTimeDelta = Math.min(scrollAt - latestScrollAt, 5 * 60 * 1000); // limit max time-delta to 5 minutes
if(scrollTopDelta !== 0) {
latestScrollTop = scrollTop;
latestScrollAt = scrollAt;
accumScrollMove += scrollTopDelta;
accumScrollTime += scrollTimeDelta;
}
// 2. Check event firing condition
if(accumScrollTime > 30 * 1000 && scrollTop / document.body.scrollHeight > 0.8) {
var pixelPerSec = Math.floor(accumScrollMove / accumScrollTime * 1000);
var label = pixelPerSec > 100 ? 'skimmer' : 'reader';
dataLayer.push({ 'event' : 'trackEvent', 'eventCategory' : 'read', 'eventAction' : 'pps', 'eventLabel' : label, 'eventValue': pixelPerSec });
ga('send', 'event', 'read', 'pps', label, pixelPerSec);
} else {
window.setTimeout(checkScroll, 500);
}
}
checkScroll();
});
} catch(e) {}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment