views:

259

answers:

4

I have an MVC app with several <a> tags, and I want to have a way of tracking link clicks, preferably without doing redirects (i.e., without changing link addresses). Is there any way this can be done? And, if not, is there any way one can get this functionality automatically (e.g., with javascript)?

Thanks.

A: 

Consider using Google Analytics: you can't do any better.

Anton Gogolev
I'm already using GA, but if the link goes off-site or downloads a local resource (e.g., a PDF), I can't track it.
Dmitri Nesteruk
+2  A: 

UPDATE

Taking your other wishes in consideration, this should be your way to go:

<script type="text/javascript">
$(document).ready(function() {  //On document ready
    $('a').click(function(e) {  //For each a (anchor), set the following function
        urchinTracker (this.href); 
        pageTracker._trackPageview (this.href);
        //Custom tracker here?
        return true; //To keep following href definitions
    });
});
</script>
Ropstah
Oh, this is jQuery, but that's included in MVC so...... ;)
Ropstah
What's the difference between returning `true` and `false` on execution?
Dmitri Nesteruk
Please see the updated answer, this might help you
Ropstah
+1  A: 

Since you are already using Google Analytics, they have a javascript function to put in the onclick event.

The method name is either urchinTracker or pageTracker._trackPageview depending on whether you are using urchin.js or ga.js as your Analytics script include.

An example (from here) in both formats:

<a href="/files/map.pdf" onClick="javascript:urchinTracker ('/downloads/map');">
<a href="/files/map.pdf" onClick="javascript:pageTracker._trackPageview ('/downloads/map');">

Basically what that does is call the javascript method (which does the 'analytics call' to Google's server) then does the <a> action as normal (ie. whatever the link was supposed to do - in this case open PDF files).

Is that what you are looking for - or is the jQuery answer what you wanted?

EDIT: in response to your question, this post contains a non-jQuery javascript include (here) that looks for 'downloadable files' and adds tracking. If you want to use jQuery, check out the other answer by ropstah since he/she has updated their answer to be Google Analytics-specific.

CraigD
Actually, this is pretty good! Can you suggest a way of automatically adding the onClick handler using jQuery? I can't go through all pages and add an onClick handler to each anchor tag, so I'm guessing there ought to be a jQuery way of doing this. Thanks in advance!
Dmitri Nesteruk
A: 

Consider Woopra

cottsak