Created
January 25, 2019 14:24
-
-
Save jvvlimme/ee5523ab0131f31eb717d220a439a054 to your computer and use it in GitHub Desktop.
This file contains 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
(function(w, d, ga){ | |
var longStay = 0, scrollsDeep; | |
// Check how deep down the page a user has scrolled | |
function getScrollPercent() { | |
var h = document.documentElement, | |
b = document.body, | |
st = 'scrollTop', | |
sh = 'scrollHeight'; | |
return Math.floor((h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100); | |
} | |
function fireEvent() { | |
// We only fire an event if GA is loaded and if either the visitor is more than 5 seconds on the page or | |
// if he has scrolled more 25% deep but not when both conditions occured | |
if (ga && (longStay || scrollsDeep) && !(longStay && scrollsDeep)) { | |
ga('send', { | |
hitType: "event", | |
eventCategory: "bounce", | |
eventAction: "interaction", | |
}) | |
} | |
} | |
// Listen to scroll events and fire an event if the user reaches 25% but not when it already has fired | |
d.addEventListener("scroll", function() { | |
if (getScrollPercent() > 25 && !scrollsDeep) { | |
scrollsDeep = 1; | |
fireEvent(); | |
} | |
}) | |
// If the user stays on the page for more than 5 seconds | |
setTimeout(function() { | |
longStay = 1; | |
fireEvent(); | |
}, 5000) | |
})(window, document, ga); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment