-
Notifications
You must be signed in to change notification settings - Fork 245
/
jquery.scrolldepth.js
executable file
·360 lines (283 loc) · 10.3 KB
/
jquery.scrolldepth.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/*!
* @preserve
* jquery.scrolldepth.js | v1.2.0
* Copyright (c) 2020 Rob Flaherty (@robflaherty)
* Licensed under the MIT and GPL licenses.
*/
/* Universal module definition */
(function(factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function($) {
/* Scroll Depth */
"use strict";
var defaults = {
minHeight: 0,
elements: [],
percentage: true,
userTiming: true,
pixelDepth: true,
nonInteraction: true,
gaGlobal: false,
gtmOverride: false,
trackerName: false,
dataLayer: 'dataLayer'
};
var $window = $(window),
cache = [],
scrollEventBound = false,
lastPixelDepth = 0,
universalGA,
classicGA,
gaGlobal,
globalSiteTag,
standardEventHandler;
/*
* Plugin
*/
$.scrollDepth = function(options) {
var startTime = +new Date;
options = $.extend({}, defaults, options);
// Return early if document height is too small
if ( $(document).height() < options.minHeight ) {
return;
}
/*
* Determine which version of GA is being used
* "ga", "__gaTracker", _gaq", and "dataLayer" are the possible globals
*/
if (options.gaGlobal) {
universalGA = true;
gaGlobal = options.gaGlobal;
} else if (typeof gtag === "function") {
globalSiteTag = true;
gaGlobal = 'gtag';
} else if (typeof ga === "function") {
universalGA = true;
gaGlobal = 'ga';
} else if (typeof __gaTracker === "function") {
universalGA = true;
gaGlobal = '__gaTracker';
}
if (typeof _gaq !== "undefined" && typeof _gaq.push === "function") {
classicGA = true;
}
if (typeof options.eventHandler === "function") {
standardEventHandler = options.eventHandler;
} else if (typeof window[options.dataLayer] !== "undefined" && typeof window[options.dataLayer].push === "function" && !options.gtmOverride) {
standardEventHandler = function(data) {
window[options.dataLayer].push(data);
};
}
/*
* Functions
*/
function sendEvent(action, label, scrollDistance, timing) {
var command = options.trackerName ? (options.trackerName + '.send') : 'send';
if (standardEventHandler) {
standardEventHandler({'event': 'ScrollDistance', 'eventCategory': 'Scroll Depth', 'eventAction': action, 'eventLabel': label, 'eventValue': 1, 'eventNonInteraction': options.nonInteraction});
if (options.pixelDepth && arguments.length > 2 && scrollDistance > lastPixelDepth) {
lastPixelDepth = scrollDistance;
standardEventHandler({'event': 'ScrollDistance', 'eventCategory': 'Scroll Depth', 'eventAction': 'Pixel Depth', 'eventLabel': rounded(scrollDistance), 'eventValue': 1, 'eventNonInteraction': options.nonInteraction});
}
if (options.userTiming && arguments.length > 3) {
standardEventHandler({'event': 'ScrollTiming', 'eventCategory': 'Scroll Depth', 'eventAction': action, 'eventLabel': label, 'eventTiming': timing});
}
} else if (globalSiteTag) {
gtag('event', action, {
'event_category': 'Scroll Depth',
'event_label': label,
'value': 1,
'non_interaction': options.nonInteraction
});
if (options.pixelDepth && arguments.length > 2 && scrollDistance > lastPixelDepth) {
lastPixelDepth = scrollDistance;
gtag('event', 'Pixel Depth', {
'event_category': 'Scroll Depth',
'event_label': rounded(scrollDistance),
'value': 1,
'non_interaction': options.nonInteraction
});
}
if (options.userTiming && arguments.length > 3) {
gtag('event', 'timing_complete', {
'event_category': 'Scroll Depth',
'name': action,
'event_label': label,
'value': timing
});
}
} else {
if (universalGA) {
window[gaGlobal](command, 'event', 'Scroll Depth', action, label, 1, {'nonInteraction': options.nonInteraction});
if (options.pixelDepth && arguments.length > 2 && scrollDistance > lastPixelDepth) {
lastPixelDepth = scrollDistance;
window[gaGlobal](command, 'event', 'Scroll Depth', 'Pixel Depth', rounded(scrollDistance), 1, {'nonInteraction': options.nonInteraction});
}
if (options.userTiming && arguments.length > 3) {
window[gaGlobal](command, 'timing', 'Scroll Depth', action, timing, label);
}
}
if (classicGA) {
_gaq.push(['_trackEvent', 'Scroll Depth', action, label, 1, options.nonInteraction]);
if (options.pixelDepth && arguments.length > 2 && scrollDistance > lastPixelDepth) {
lastPixelDepth = scrollDistance;
_gaq.push(['_trackEvent', 'Scroll Depth', 'Pixel Depth', rounded(scrollDistance), 1, options.nonInteraction]);
}
if (options.userTiming && arguments.length > 3) {
_gaq.push(['_trackTiming', 'Scroll Depth', action, timing, label, 100]);
}
}
}
}
function calculateMarks(docHeight) {
return {
'25%' : parseInt(docHeight * 0.25, 10),
'50%' : parseInt(docHeight * 0.50, 10),
'75%' : parseInt(docHeight * 0.75, 10),
// Cushion to trigger 100% event in iOS
'100%': docHeight - 5
};
}
function checkMarks(marks, scrollDistance, timing) {
// Check each active mark
$.each(marks, function(key, val) {
if ( $.inArray(key, cache) === -1 && scrollDistance >= val ) {
sendEvent('Percentage', key, scrollDistance, timing);
cache.push(key);
}
});
}
function checkElements(elements, scrollDistance, timing) {
$.each(elements, function(index, elem) {
if ( $.inArray(elem, cache) === -1 && $(elem).length ) {
if ( scrollDistance >= $(elem).offset().top ) {
sendEvent('Elements', elem, scrollDistance, timing);
cache.push(elem);
}
}
});
}
function rounded(scrollDistance) {
// Returns String
return (Math.floor(scrollDistance/250) * 250).toString();
}
function init() {
bindScrollDepth();
}
/*
* Public Methods
*/
// Reset Scroll Depth with the originally initialized options
$.scrollDepth.reset = function() {
cache = [];
lastPixelDepth = 0;
$window.off('scroll.scrollDepth');
bindScrollDepth();
};
// Add DOM elements to be tracked
$.scrollDepth.addElements = function(elems) {
if (typeof elems == "undefined" || !$.isArray(elems)) {
return;
}
$.merge(options.elements, elems);
// If scroll event has been unbound from window, rebind
if (!scrollEventBound) {
bindScrollDepth();
}
};
// Remove DOM elements currently tracked
$.scrollDepth.removeElements = function(elems) {
if (typeof elems == "undefined" || !$.isArray(elems)) {
return;
}
$.each(elems, function(index, elem) {
var inElementsArray = $.inArray(elem, options.elements);
var inCacheArray = $.inArray(elem, cache);
if (inElementsArray != -1) {
options.elements.splice(inElementsArray, 1);
}
if (inCacheArray != -1) {
cache.splice(inCacheArray, 1);
}
});
};
/*
* Throttle function borrowed from:
* Underscore.js 1.5.2
* http://underscorejs.org
* (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Underscore may be freely distributed under the MIT license.
*/
function throttle(func, wait) {
var context, args, result;
var timeout = null;
var previous = 0;
var later = function() {
previous = new Date;
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = new Date;
if (!previous) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
}
/*
* Scroll Event
*/
function bindScrollDepth() {
scrollEventBound = true;
$window.on('scroll.scrollDepth', throttle(function() {
/*
* We calculate document and window height on each scroll event to
* account for dynamic DOM changes.
*/
var docHeight = $(document).height(),
winHeight = window.innerHeight ? window.innerHeight : $window.height(),
scrollDistance = $window.scrollTop() + winHeight,
// Recalculate percentage marks
marks = calculateMarks(docHeight),
// Timing
timing = +new Date - startTime;
// If all marks already hit, unbind scroll event
if (cache.length >= options.elements.length + (options.percentage ? 4:0)) {
$window.off('scroll.scrollDepth');
scrollEventBound = false;
return;
}
// Check specified DOM elements
if (options.elements) {
checkElements(options.elements, scrollDistance, timing);
}
// Check standard marks
if (options.percentage) {
checkMarks(marks, scrollDistance, timing);
}
}, 500));
}
init();
};
// UMD export
return $.scrollDepth;
}));