Created
October 25, 2016 17:52
-
-
Save ericorruption/0c57a52f2f96369c611dde7c4f7c5e5c to your computer and use it in GitHub Desktop.
track elements on screen
This file contains hidden or 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
/* global ga */ | |
function throttle(callback, limit) { | |
let wait = false; | |
return function() { | |
if (!wait) { | |
callback.call(); | |
wait = true; | |
setTimeout(function() { | |
wait = false; | |
}, limit); | |
} | |
} | |
} | |
function isElementOnScreen(elementId) { | |
const windowHeight = window.innerHeight; | |
const windowPos = document.body.scrollTop; | |
const el = document.getElementById(elementId); | |
return el.offsetTop < windowHeight + windowPos; | |
} | |
let trackedOffers = false; | |
let trackedForm = false; | |
const trackElements = throttle(function() { | |
if (isElementOnScreen('offers') && !trackedOffers) { | |
trackedOffers = true; | |
ga('send', 'event', 'Scroll', 'Page viewed', 'Ofertas'); | |
} | |
if (isElementOnScreen('contact-form') && !trackedForm) { | |
trackedForm = true; | |
ga('send', 'event', 'Scroll', 'Page viewed', 'Form'); | |
} | |
if (trackedOffers && trackedForm) { | |
window.removeEventListener('scroll', trackElements); | |
} | |
}, 100); | |
window.addEventListener('scroll', trackElements); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment