Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Basic Scroll Tracking Example
* @serpsapp
*/
/**
* get the current scroll depth
* @return {integer} depth as percentage
*/
function getDepth()
{
return Math.floor(
(
(window.pageYOffset + window.innerHeight) /
document.body.scrollHeight
) * 100
)
}
var depth = getDepth()
var didScroll = false
/**
* before unload callback
* send GA event with max depth
*/
function beforeUnload()
{
ga('send', 'event', 'Category', 'Action', 'Label', depth)
}
/**
* scroll callback
* set didScroll to true
*/
function onScroll()
{
didScroll = true
}
// attach scroll event handler
window.addEventListener("scroll", onScroll)
// attach beforeunload event handler
window.addEventListener("beforeunload", beforeUnload)
/**
* throttled scroll event
* checks whether didScroll is true every 100ms
* then returns it to false
*/
function throttleScroll()
{
if(didScroll){
var tempDepth = getDepth()
if(tempDepth > depth){
depth = tempDepth
}
didScroll = false
}
setTimeout(throttleScroll, 100)
}
setTimeout(throttleScroll, 100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment