Last active
February 27, 2019 22:59
-
-
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.
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
/** | |
* 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