JSFiddle - React, Tailwind, and code Playground
by andyw_
HTML
<script type="text/javascript">
var _gaq = _gaq || [];
(function() {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
<a href="somewhere.com">Somewhere</a>
JavaScript
/**
** GA_trackEvent.js
** jQuery plugin that makes custom google event tracking much easier.
**
** @param toPush the arrays/array to be pushed i.e. [[], [], []] or []
** @param options (optional extra's)
** --OPTIONAL--
** debugMode: bool false - gives useful debugging messages via console
** eventTricker: string 'click' - the event that triggers this plugins actions
** triggerOnce: bool false - only triger ga event tracking during the first time the event gets triggered
** preventDefault: bool false - whether to use or not to use default event handler after ga event tracking gets pushed
** afterHandler: callback function(elem) {} - callback after the entire handler's been completed executed
** afterPush: callback function(elem) {} - callback after event tracking has been executed, but before the default handler (if preventDefault if false)
** gets executed
*/
(function($){
$.GA_trackEvent = function(el, toPush, options){
// To avoid scope issues, use 'base' instead of 'this'
// to reference this class from internal events and functions.
var base = this;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
// Add a reverse reference to the DOM object
base.$el.data("GA_trackEvent", base);
base.func = [];
//Attach tracking event to element
base.func.attachTracker = function(){
base.$el.bind(base.options.eventTrigger, base.func.eventHandler);
};
//Our event handler for pushing to gaq object
base.func.eventHandler = function(e){
base.log('the element has been clicked');
base.func.gaPush(toPush); //push
base.options.afterPush(base.el); //after push callback
//execute normal events effect if prevent default is...