sf_tristanb
sf_tristanb

Reputation: 8855

jQuery code to track clicks on outgoing links (Google Analytics)

I found this on the web:

$('a[href^=http]:not("[href*=://' + document.domain + ']")').click(function() {
 pageTracker._trackPageview('/outgoing/' + $(this).attr('href'));
});

But it's not working. In my Google Analytics account there are no /outgoing/ links showing (it's been 24+ hours since I implemented it).

What's wrong with this code? I'm using jQuery of course ;)

I already have:

<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>

<script type="text/javascript">
try {
  var pageTracker = _gat._getTracker("UA MY CODE");
  pageTracker._trackPageview();
} catch(err) {}
</script>

Upvotes: 0

Views: 1247

Answers (2)

Jeffery To
Jeffery To

Reputation: 11936

Try (note the double quotes for attribute values and not for :not()):

$('a[href^="http"]:not([href*="://' + document.domain + '"])').click(function() {
    pageTracker._trackPageview('/outgoing/' + $(this).attr('href'));
});

Also, are your links static (on the HTML page) or dynamic (generated by JavaScript)? If you add links after this code you will need to call this code again to attach the click event handler.

Upvotes: 1

GlenCrawford
GlenCrawford

Reputation: 3389

I think you need to also include the Google Analytics external JavaScript file. Place the following code at the end of your page's body (untested):

var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

A more detailed "how to" by Google can be found here: clicky

Upvotes: 0

Related Questions