Created
October 16, 2019 06:52
-
-
Save GrahamLea/b0062b80405fdb78973703a6d0c5fa5a to your computer and use it in GitHub Desktop.
HTML/JS embed source to get a Carrd web page logging scroll depth events to Google Analytics (should work for any website loading GA via https://www.googletagmanager.com/gtag/js?id=UA-XXXXX-X)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
// TODO: Replace the percentages and names below with those relevant to your website | |
var percentagesToReport = new Map(); | |
percentagesToReport.set(25, 'Section2'); | |
percentagesToReport.set(50, 'Section3'); | |
percentagesToReport.set(75, 'Section4'); | |
percentagesToReport.set(90, 'Section5'); | |
function reportScroll(scrollLocationName) { | |
gtag('event', scrollLocationName, { | |
'event_category': 'Scrolling', | |
'event_label': '{{Page URL}}', | |
'non_interaction': true | |
}); | |
} | |
document.addEventListener('scroll', function() { | |
var h = document.documentElement, | |
b = document.body, | |
st = 'scrollTop', | |
sh = 'scrollHeight'; | |
var percent = parseInt ( (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100); | |
// console.log(percent + "%"); // Uncomment to debug all scrolling to console | |
if (percentagesToReport.has(percent)) { | |
var scrollLocationName = percentagesToReport.get(percent); | |
console.log("Reporting " + percent + "% scroll (" + scrollLocationName + ") to GA"); | |
reportScroll('S' + percent + ':' + scrollLocationName); | |
percentagesToReport.delete(percent); | |
} | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment