Skip to content

Instantly share code, notes, and snippets.

@ericorruption
Created October 25, 2016 17:52
Show Gist options
  • Save ericorruption/0c57a52f2f96369c611dde7c4f7c5e5c to your computer and use it in GitHub Desktop.
Save ericorruption/0c57a52f2f96369c611dde7c4f7c5e5c to your computer and use it in GitHub Desktop.
track elements on screen
/* 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