Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Basic scroll tracking with adjusted bounce rate
* @serpsapp
*/
var scrollThreshold = 10
var timeThreshold = 15
var nonInteractive = true
/**
* 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, {
nonInteractive : nonInteractive
})
}
/**
* 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
}
if(depth >= scrollThreshold){
nonInteractive = false
}
didScroll = false
}
setTimeout(throttleScroll, 100)
}
setTimeout(throttleScroll, 100)
/**
* nonInteractive time threshold timer
* trigger once after timeThreshold
*/
function pageTimer()
{
nonInteractive = false
}
// *1000 to convert s to ms
setTimeout(pageTimer, timeThreshold * 1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.