Skip to content

Instantly share code, notes, and snippets.

@marcaube
Last active August 29, 2015 13:56
Show Gist options
  • Save marcaube/8963630 to your computer and use it in GitHub Desktop.
Save marcaube/8963630 to your computer and use it in GitHub Desktop.
Track outbound links using google analytics. This script pushes an event when clicking on <a> tags with the `js-ext` class.
/**
* Utility to wrap the different behaviors between W3C-compliant browsers
* and IE when adding event handlers.
*
* @param {Object} elem The element on which to attache the event listener
* @param {string} event The event type to listen for (e.g. load, click, etc.)
* @param {function()} callback The callback function that receives the notification
*/
function addListener(elem, event, callback) {
// W3C
if (elem.addEventListener) {
elem.addEventListener(event, callback);
return true;
}
// IE
else if (elem.attachEvent) {
return elem.attachEvent('on' + event, callback);
}
return false;
}
/**
* Track events on all links with the js-ext class
*/
document.addEventListener('DOMContentLoaded', function() {
[].forEach.call(document.querySelectorAll(".js-ext"), function(el) {
addListener(el, "click", function(event) {
var title = el.dataset.title,
link = el.href,
label;
// If data-title is empty, use the href as the event label
label = (title === undefined) ? link : title;
console.log('Click on ' + label);
try {
// Old Google Analytics
if (typeof _gaq !== "undefined") {
_gaq.push(['_trackEvent', 'Outbound Links', 'click', label]);
}
// New Google Analytics
if (typeof ga !== "undefined") {
ga('send', 'event', 'Outbound Links', 'click', label);
}
} catch(err) {
console.log(err);
}
// Delay by .5s if link target is not _blank, so that GA can track the event
if (!el.target || el.target.match(/^_(self|parent|top)$/i)) {
setTimeout(function() {
document.location.href = link;
}.bind(el), 500);
event.preventDefault ? event.preventDefault() : event.returnValue = !1;
}
});
});
});
@marcaube
Copy link
Author

Instead of binding the event to all links with the js-ext class (on line #29), we can also use the following selector to target all links whose href starts with http and doesn't contain your domain name

document.querySelectorAll("a[href^='http']:not([href*='yourdomain.com'])")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment