Skip to content

Instantly share code, notes, and snippets.

@chrisgoddard
Last active May 10, 2016 21:31
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/769c690f753dcdb0adae27617c2cf00c to your computer and use it in GitHub Desktop.
Save chrisgoddard/769c690f753dcdb0adae27617c2cf00c to your computer and use it in GitHub Desktop.
/**
* 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