-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlink-click-analytics.js
79 lines (60 loc) · 2.38 KB
/
link-click-analytics.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/***************************************************
* This script searches for links that have a data attribute and attaches Google Analtics Event Tracking to them.
*
* This script takes in to account modifier keys to open links in new tabs.
*
* To run this script, simply include it anywhere on the page.
*
* https://github.com/bcole808/link-click-analytics
***************************************************/
(function ($) {
if (typeof $ == 'undefined') {
return console.warn("jQuery is not loaded!");
}
var linkAnalytics = {
initialize : function() {
$('body').on('click', '[data-analytics-event]', linkAnalytics.trackAction);
}, // end initialize
trackAction : function(e) {
/***************************************************
* Event attributes:
*
* Category (required), Action (required), Label (optional), value (optional)
*
* More information: https://developers.google.com/analytics/devguides/collection/analyticsjs/events
***************************************************/
var attr_string = $(e.currentTarget).attr('data-analytics-event');
// Do nothing if undefined
if (!attr_string) return true;
var attributes = attr_string.split(",");
var href_url = $(e.currentTarget).attr('href') || false;
var modifierKey = (e.metaKey || e.ctrlKey);
var ga_category = attributes[0] || 'Call to Action Link';
var ga_action = attributes[1] || $(e.currentTarget).text() || 'Click';
var ga_label = attributes[2] || $(e.currentTarget).attr('href') || undefined;
var ga_value = parseInt(attributes[3]) || undefined;
// Check for Google Universal Analytics
if (typeof(ga) !== 'undefined') {
// Send event to Google Analytics
ga('send', 'event', ga_category, ga_action, ga_label, ga_value);
// Check for ga.js
} else if (typeof(_gaq) !== 'undefined') {
// Send event to Google Analytics
_gaq.push(['_trackEvent', ga_category, ga_action, ga_label, ga_value]);
// Navigate browser to the URL
if (href_url && !modifierKey) {
setTimeout(function() {
window.location.href = href_url;
}, 250);
e.preventDefault();
return false;
}
} else {
console.log("Google Analytics is not running, so no Google Analytics tracking data could be sent.")
}
} // end trackAction()
}; // end linkAnalytics
$(document).ready( function() {
linkAnalytics.initialize();
});
})(jQuery);