0121 31 45 374
Qoute Icon

Track Google Analytics and Google AdWords conversions on click with jQuery

Tim

Today we needed to track conversions in Google Analytic and Google AdWords when a user clicked a button. There are a fair few posts around with different ways to do this but as it's something we've needed to do before so I thought I'd wrap it up into a quick jQuery plugin.

I've popped the script below for you and on github as a gist here: https://gist.github.com/3946934

Please note: To track Google Analytics, you will need to make sure that the standard Google Analytics tracking code (the new version) is included on your page.

The jQuery Plugin

/*!
* Conversion Tracker: a jQuery Plugin that tracks an event in both Google Analytics and Google AdWords
* @author: Tim Gaunt (@timgaunt)
* @url: http://blogs.thesitedoctor.co.uk/tim
* @documentation: http://blogs.thesitedoctor.co.uk/tim
* @published: 24/10/2012
* @license Creative Commons Attribution Non-Commercial Share Alike 3.0 Licence
*		   http://creativecommons.org/licenses/by-nc-sa/3.0/
*
* ----------------------
* Usage
* ----------------------
* $('a').trackConversion({ goalId: Your AdWords Id });
*
*/
;if(typeof jQuery != 'undefined') {
	jQuery(function($) {
		$.fn.extend({
			trackConversion: function(options) {
				var settings = $.extend({}, $.fn.trackConversion.defaults, options);
			
				return this.each(function () {
					var $$	= $(this),
						o	= $.metadata ? $.extend({}, settings, $$.metadata()) : settings;

					$$.click(function(e){
						if(getValue($$, o.trackAnalytics) && (typeof _gaq != 'undefined')){
							_gaq.push(['_trackEvent', getValue($$, o.label), getValue($$, o.action), getValue($$, o.value)]);
						}
						
						if(getValue($$, o.trackAdWords) && getValue($$, o.goalId) > 0){
							var randomNum = new Date().getMilliseconds();
							var trackUrl = "http://www.googleadservices.com/pagead/conversion/" + getValue($$, o.goalId) + "/?random=" + randomNum + "&value=" + getValue($$, o.conversionValue) + "&label=" + getValue($$, o.label) + "&guid=ON&script=0&url=" + getValue($$, o.url);
							$('<img />', {src:trackUrl, width:1, height:1 }); 
						}
					});
				});

				function getValue(link, value) {
					return (typeof value !== "function") ? value : value(link);
				}
			}
		});

		$.fn.trackConversion.defaults = {
			trackAnalytics:true,
			trackAdWords:true,
			url: function(){ return encodeURI(location.href); },
			goalId: 0,
			label: "Conversion",
			action: "Click",
			value: "",
			conversionValue: 1
		};

	}(jQuery));
}

Liked this post? Got a suggestion? Leave a comment