I have some tracking code that does the following and is bound to the click event on all <a>
tags (the setTimeout
is per the recommendations on Google's site, necessary to allow the tracking event to fire before the unload event, I guess):
$.fn.trackClick = function (e) {
// track the click
try {
_gaq.push(['_trackEvent', 'clicked-link', this.parents('[id]:first').get(0).id, (this.text() || this.children('img:first').attr('alt'))]);
} catch (err) {}
//only reload links with no bound events
if (!this.data('events') && !this.get(0).onclick && !e.isDefaultPrevented()) {
// wait a moment for the tracking to process, then follow the link
setTimeout('document.location = "' + $(this).attr('href') + '"', 200);
}
}
The problem is, we have literally hundreds of links on our site, some of which don't actually reload anything (dialog closing buttons, for example), so I need the setTimeout
to only run when there isn't already a JS event bound to the element (or up the DOM tree). I came up with the if statement above, which I think accounts for any and all possible bound events (the codebase spans several years, so there could be all kinds of foolishness in there). Does anyone else have a better way to do this, or am I missing some possible event checks?
UPDATE: This is probably key, and I should have mentioned it earlier. The function above is being called in a delegated manner, so events in parent divs actually fire first (hence my need to detect them).
jQuery(document).delegate('a', 'click', function(e){
e.preventDefault();
$(this).trackClick();
});