2

I've got a jQuery routine I need to convert to MooTools, but I can't get it to work. Here's my jQuery version:

$(".google-analytics-link").click(function () {
    var href = $(this).attr("href");
    pageTracker._link(href);
    location.href = href;
    return false;
});

Here's my MooTools translation:

$$(".google-analytics-link").addEvent("click", function () {
    var href = this.get("href");
    pageTracker._link(href);
    location.href = href;
    return false;
});

Doesn't seem to work though. I don't understand MooTools selectors. Any help, please?

1
  • 1
    there is nothing wrong with your translation. in mootools 1.2.4+ $$ is being deprecated in favour of document.getElements() though, i have seen a few instances where $$ (which is an alias for this.document.getElements) fails. here's a jsfiddle that proves it all works: jsfiddle.net/dimitar/KGRFM. it's far more likely that it works but fails to track due to the click event navigating away before the tracking can take place. in moo, you tend to stop the original events by passing on the event object to the callback fn (in this case, e and apply the .stop(); method, not return false Commented Sep 8, 2010 at 19:46

2 Answers 2

2

You don't need to explicitly set the window's location when clicking the link already does it. Currently the code stops the native event, calls a method on the pageTracker object, then redirects to the location of the clicked link.

Google Analytics documentation for the _link method says that

This method works in conjunction with the _setDomainName() and _setAllowLinker() methods to enable cross-domain user tracking. The _link() method passes the cookies from this site to another via URL parameters (HTTP GET). It also changes the document.location and redirects the user to the new URL.

implying that you simply have to stop the click event, and call the _link method which will take care of the rest.

var analyticsLinks = document.getElements('.google-analytics-link');

analyticsLinks.addEvent('click', function(event) {
    // stop the page from navigating away
    event.stop();
    var href = this.get('href');
    // let the Analytics API do its work, and then redirect to this link
    pageTracker._link(href);
});
0
1
$$(".google-analytics-link").each(function (e) { 
    e.addEvent("click", function () {
        var href = this.get("href");
        pageTracker._link(href);
        location.href = href;
        return false;
    });
});
1
  • 1
    $$(selector).addEvent() will automatically iterate through the whole element collection returned by $$, does that since 1.1x(?) - so this is probably not it. Commented Sep 8, 2010 at 19:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.