Change the location of your external links with MooTools

So a thing I was trying to do for quite some time now but using php and rexep, which I hate and don’t understand at all, was trying to change the location (href) of all the external links on my page to something else so I could easily track the clicks. Or maybe display some kind of toolbar on top of the page, something like I guess digg does.

Today I remembered that MooTools is my friend and I could use it to accomplish this.. and after 2 minutes and 5 lines of code I did it!

I’m guessing you already have MooTools up and running. Let’s take a look at the code.

$$('a').each(function(link) {
    if(link.hostname != window.location.host) {
        var loc = link.get('href');
        link.set('href', './out.php?' + loc);
    }
});

So we create an array of all the links on our site and check if their hostname is the same as the hostname of our site. If it is different we read the value of href (the link) and change it to our php script that is going to track the click (or whatever) and add the previous link, so it knows where it should be redirected.

This is it! Easy peasy!

Oh and have a happy December!

If you liked this post think about subscribing to my RSS feed and prevent missing anything interesting. It's free, fast and doesn't hurt. Promise. Click here.
Related posts: