-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathattribute-tracking-paq.js
More file actions
67 lines (60 loc) · 2.27 KB
/
Copy pathattribute-tracking-paq.js
File metadata and controls
67 lines (60 loc) · 2.27 KB
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
// Data-attribute tracking by
// Tomas Persson - Digitalist.se
// This script will send events directly to Matomo (will not use TagManager)
/**
Usage:
Add this script to any page where you have the Matomo script running.
The script will catch clicks on elements with the data attribute data-event-category or data-event-include
An example would be
<div data-event-category="Button"
data-event-action="Click"
data-event-name="Buy Milk"
data-event-value="4">
<a href="https://example.com" data-event-include>Click Me!</a>
<i class="arrow" data-event-include>
</div>
**/
//Get Matomo
var _paq = window._paq = window._paq || [];
// Send data to Matomo function
function sendEventData(elem) {
let action = "";
if(elem.getAttribute('data-event-action') != null)
action = elem.getAttribute('data-event-action');
let name = "";
if(elem.getAttribute('data-event-name') != null)
name = elem.getAttribute('data-event-name');
let value = 0;
if(elem.getAttribute('data-event-value') != null)
value = elem.getAttribute('data-event-value');
_paq.push(['trackEvent',
elem.getAttribute('data-event-category'),
action,
name,
value]);
}
// Javascript polyfill for the function .closest for IE9+
if (!Element.prototype.matches) {
Element.prototype.matches = Element.prototype['msMatchesSelector'] || Element.prototype.webkitMatchesSelector;
}
if (!Element.prototype.closest) {
Element.prototype.closest = function(s) {
var el = this;
do {
if (el.matches(s)) {
return el;
}
el = el.parentElement || el.parentNode;
} while (el !== null && el.nodeType === 1);
return null;
};
}
// END - Javascript polyfill for the function .closest for IE9+
// Detect clicks on elements with data attribute data-event-category or data-event-include
document.documentElement.addEventListener('click', function(event) {
if (event.target.getAttribute('data-event-category') != null) {
sendEventData(event.target);
} else if (event.target.getAttribute('data-event-include') != null) {
sendEventData(event.target.closest('[data-event-category]'));
}
}, true);