Created
October 24, 2012 15:59
-
-
Save timgaunt/3946934 to your computer and use it in GitHub Desktop.
Google Analytics and Google AdWords link and button click tracker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* 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)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment