Skip to content

Instantly share code, notes, and snippets.

@robflaherty
Created February 28, 2010 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robflaherty/317855 to your computer and use it in GitHub Desktop.
Save robflaherty/317855 to your computer and use it in GitHub Desktop.
Simple Google Analytics event tracking. Tracks external links, downloads, and mailtos
document.onclick = function(event) {
event = event || window.event;
var target = event.target || event.srcElement,
targetElement = target.tagName.toLowerCase();
if (targetElement == "a") {
var href = target.getAttribute("href"),
urlHost = document.domain.replace(/^www\./i,"");
var urlPattern = "^(?:https?:)?\/\/(?:(?:www)\.)?" + urlHost + "\/?";
eventCheck(href,urlPattern);
}
function eventCheck(href,urlPattern){
if ((href.match(/^https?\:/i)) && (!href.match(urlPattern))){
if (href.match(/^.*\.(pdf|jpg|png|gif|zip|mp3|txt|doc|rar|js|py)$/i)) {
_gaq.push(['_trackEvent', 'Download', 'click', href]);
} else {
_gaq.push(['_trackEvent', 'External', 'click', href]);
}
} else if (href.match(/^mailto\:/i)) {
_gaq.push(['_trackEvent', 'Email', 'click', href.substr(7)]);
} else if (href.match(/^.*\.(pdf|jpg|png|gif|zip|mp3|txt|doc|rar|js|py)$/i)) {
_gaq.push(['_trackEvent', 'Download', 'click', href]);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment