Analytics & Testing

Append Google Analytics Campaign Querystring Dynamically using jQuery

Friend Todd Baker sent me a solution via Twitter for a problem that I haven’t had an opportunity to develop a solution for. Since our blogs on Compendium are sometimes hosted on a secondary domain for a client, we’d like to pass Google Analytics campaign code to the primary domain so they can track visitors effectively.

Another difficulty, though, is ensuring your bloggers always include a campaign code… something that should not be expected. The correct solution is to utilize JavaScript to dynamically add the campaign code when the page loads.

document.ready(function() {
var campaignQueryString = '?{fill this in}';
var targetDomain = '{fill this in}';
$("a[href='http://www." + targetDomain + "]'").each(function() {
this.href += campaignQueryString;
});
});

This specific solution uses and requires jQuery, an open source JavaScript framework. I’m a big fan of jQuery to add some nice effects to web sites . I have heard feedback that some enterprise developers don’t appreciate trying to keep up with the versioning, though.

If you use the above code, you must include jQuery. I’d recommend loading it from Google. Since many people are doing this, your page will load much faster since the code is cached, having been loaded before.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>

Google even supplies a URL Builder to show you how to build your campaign querystring. If you want to really get fancy, I’d recommend adding in elements like keywords, categories, authors, etc.

One comment

  1. 1

Leave a Reply