Skip to content

Instantly share code, notes, and snippets.

@chrisgoddard
Last active May 10, 2016 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisgoddard/90e6e8ee16eceadc772aea7236f5e1d2 to your computer and use it in GitHub Desktop.
Save chrisgoddard/90e6e8ee16eceadc772aea7236f5e1d2 to your computer and use it in GitHub Desktop.
/**
* 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