1

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();
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
brandwaffle
  • 1,252
  • 9
  • 11
  • See this related question: http://stackoverflow.com/questions/1236067/test-if-event-handler-is-bound-to-an-element-in-jquery – George Dec 21 '11 at 18:04
  • I appreciate the input, but please note the part about bubbled events as well. If this.data('events') was working for all cases, I wouldn't already have 2 additional checks in there. There's also a snarky comment in the other question about inline handlers, but unfortunately I don't have the luxury of being snarky about them--they're in a bunch of legacy code and I need to deal with them. – brandwaffle Dec 21 '11 at 18:06
  • In one of the jQuery blog posts it was mentioned that storing the event bindings in `data` was to be removed/changed in future versions of jQuery. – zzzzBov Dec 21 '11 at 18:20

0 Answers0