Skip to content

Instantly share code, notes, and snippets.

@RichardDillman
Last active February 27, 2019 22:59
Show Gist options
  • Save RichardDillman/d4df28f522e5501f015551c665199a42 to your computer and use it in GitHub Desktop.
Save RichardDillman/d4df28f522e5501f015551c665199a42 to your computer and use it in GitHub Desktop.
Single event to track clicks on all elements within the page. Simply add the data-tracking-label attribute to any elements that should be tracked. If an element is clicked that does not have this attribute we walk up the DOM till we find one that does. Be sure to add a data-tracking-label on your outermost div or body.
/**
* Recursively an ancestor element with a matching attribute.
**/
const findAncestor = (el, label) => {
while ((el = el.parentElement) && !el.getAttribute(label));
return el.getAttribute(label);
}
/**
* Retrieve the attribute or its ancestor attribute.
**/
getlabel = el => {
const label = 'data-tracking-label'
return el.getAttribute(label) || findAncestor(el, label);
}
/**
* Add a click listener that watches all elements on the page.
**/
document.addEventListener('click', event => {
const label = getlabel(event.target);
// do your thing with the label
ga('send', 'event', 'page', 'click', label);
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment