Skip to content

Instantly share code, notes, and snippets.

@akngs
Last active September 22, 2022 01:38
Show Gist options
  • Save akngs/0c570304bd9a2dd9082e to your computer and use it in GitHub Desktop.
Save akngs/0c570304bd9a2dd9082e to your computer and use it in GitHub Desktop.
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