PageSourceSearch

https://jlharchitect.com/lib/fastclick/fastclick.js?c=1

js jlharchitect.com collected 2026-09-26 14:40:16 UTC 21,054 bytes, 737 lines download raw bytes

1/**
2 * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
3 *
4 * @version 0.6.7
5 * @codingstandard ftlabs-jsv2
6 * @copyright The Financial Times Limited [All Rights Reserved]
7 * @license MIT License (see LICENSE.txt)
8 */
9
10/*jslint browser:true, node:true*/
11/*global define, Event, Node*/
12
13
14/**
15 * Instantiate fast-clicking listeners on the specificed layer.
16 *
17 * @constructor
18 * @param {Element} layer The layer to listen on
19 */
20function FastClick(layer) {
21	'use strict';
22	var oldOnClick, self = this;
23
24
25	/**
26	 * Whether a click is currently being tracked.
27	 *
28	 * @type boolean
29	 */
30	this.trackingClick = false;
31
32
33	/**
34	 * Timestamp for when when click tracking started.
35	 *
36	 * @type number
37	 */
38	this.trackingClickStart = 0;
39
40
41	/**
42	 * The element being tracked for a click.
43	 *
44	 * @type EventTarget
45	 */
46	this.targetElement = null;
47
48
49	/**
50	 * X-coordinate of touch start event.
51	 *
52	 * @type number
53	 */
54	this.touchStartX = 0;
55
56
57	/**
58	 * Y-coordinate of touch start event.
59	 *
60	 * @type number
61	 */
62	this.touchStartY = 0;
63
64
65	/**
66	 * ID of the last touch, retrieved from Touch.identifier.
67	 *
68	 * @type number
69	 */
70	this.lastTouchIdentifier = 0;
71
72
73	/**
74	 * Touchmove boundary, beyond which a click will be cancelled.
75	 *
76	 * @type number
77	 */
78	this.touchBoundary = 10;
79
80
81	/**
82	 * The FastClick layer.
83	 *
84	 * @type Element
85	 */
86	this.layer = layer;
87
88	if (!layer || !layer.nodeType) {
89		throw new TypeError('Layer must be a document node');
90	}
91
92	/** @type function() */
93	this.onClick = function() { return FastClick.prototype.onClick.apply(self, arguments); };
94
95	/** @type function() */
96	this.onMouse = function() { return FastClick.prototype.onMouse.apply(self, arguments); };
97
98	/** @type function() */
99	this.onTouchStart = function() { return FastClick.prototype.onTouchStart.apply(self, arguments); };
100
101	/** @type function() */
102	this.onTouchEnd = function() { return FastClick.prototype.onTouchEnd.apply(self, arguments); };
103
104	/** @type function() */
105	this.onTouchCancel = function() { return FastClick.prototype.onTouchCancel.apply(self, arguments); };
106
107	if (FastClick.notNeeded(layer)) {
108		return;
109	}
110
111	// Set up event handlers as required
112	if (this.deviceIsAndroid) {
113		layer.addEventListener('mouseover', this.onMouse, true);
114		layer.addEventListener('mousedown', this.onMouse, true);
115		layer.addEventListener('mouseup', this.onMouse, true);
116	}
117
118	layer.addEventListener('click', this.onClick, true);
119	layer.addEventListener('touchstart', this.onTouchStart, false);
120	layer.addEventListener('touchend', this.onTouchEnd, false);
121	layer.addEventListener('touchcancel', this.onTouchCancel, false);
122
123	// Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
124	// which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
125	// layer when they are cancelled.
126	if (!Event.prototype.stopImmediatePropagation) {
127		layer.removeEventListener = function(type, callback, capture) {
128			var rmv = Node.prototype.removeEventListener;
129			if (type === 'click') {
130				rmv.call(layer, type, callback.hijacked || callback, capture);
131			} else {
132				rmv.call(layer, type, callback, capture);
133			}
134		};
135
136		layer.addEventListener = function(type, callback, capture) {
137			var adv = Node.prototype.addEventListener;
138			if (type === 'click') {
139				adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
140					if (!event.propagationStopped) {
141						callback(event);
142					}
143				}), capture);
144			} else {
145				adv.call(layer, type, callback, capture);
146			}
147		};
148	}
149
150	// If a handler is already declared in the element's onclick attribute, it will be fired before
151	// FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
152	// adding it as listener.
153	if (typeof layer.onclick === 'function') {
154
155		// Android browser on at least 3.2 requires a new reference to the function in layer.onclick
156		// - the old one won't work if passed to addEventListener directly.
157		oldOnClick = layer.onclick;
158		layer.addEventListener('click', function(event) {
159			oldOnClick(event);
160		}, false);
161		layer.onclick = null;
162	}
163}
164
165
166/**
167 * Android requires exceptions.
168 *
169 * @type boolean
170 */
171FastClick.prototype.deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0;
172
173
174/**
175 * iOS requires exceptions.
176 *
177 * @type boolean
178 */
179FastClick.prototype.deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent);
180
181
182/**
183 * iOS 4 requires an exception for select elements.
184 *
185 * @type boolean
186 */
187FastClick.prototype.deviceIsIOS4 = FastClick.prototype.deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);
188
189
190/**
191 * iOS 6.0(+?) requires the target element to be manually derived
192 *
193 * @type boolean
194 */
195FastClick.prototype.deviceIsIOSWithBadTarget = FastClick.prototype.deviceIsIOS && (/OS ([6-9]|\d{2})_\d/).test(navigator.userAgent);
196
197
198/**
199 * Determine whether a given element requires a native click.
200 *
201 * @param {EventTarget|Element} target Target DOM element
202 * @returns {boolean} Returns true if the element needs a native click
203 */
204FastClick.prototype.needsClick = function(target) {
205	'use strict';
206	switch (target.nodeName.toLowerCase()) {
207
208	// Don't send a synthetic click to disabled inputs (issue #62)
209	case 'button':
210	case 'select':
211	case 'textarea':
212		if (target.disabled) {
213			return true;
214		}
215
216		break;
217	case 'input':
218
219		// File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
220		if ((this.deviceIsIOS && target.type === 'file') || target.disabled) {
221			return true;
222		}
223
224		break;
225	case 'label':
226	case 'video':
227		return true;
228	}
229
230	return (/\bneedsclick\b/).test(target.className);
231};
232
233
234/**
235 * Determine whether a given element requires a call to focus to simulate click into element.
236 *
237 * @param {EventTarget|Element} target Target DOM element
238 * @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
239 */
240FastClick.prototype.needsFocus = function(target) {
241	'use strict';
242	switch (target.nodeName.toLowerCase()) {
243	case 'textarea':
244	case 'select':
245		return true;
246	case 'input':
247		switch (target.type) {
248		case 'button':
249		case 'checkbox':
250		case 'file':
251		case 'image':
252		case 'radio':
253		case 'submit':
254			return false;
255		}
256
257		// No point in attempting to focus disabled inputs
258		return !target.disabled && !target.readOnly;
259	default:
260		return (/\bneedsfocus\b/).test(target.className);
261	}
262};
263
264
265/**
266 * Send a click event to the specified element.
267 *
268 * @param {EventTarget|Element} targetElement
269 * @param {Event} event
270 */
271FastClick.prototype.sendClick = function(targetElement, event) {
272	'use strict';
273	var clickEvent, touch;
274
275	// On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
276	if (document.activeElement && document.activeElement !== targetElement) {
277		document.activeElement.blur();
278	}
279
280	touch = event.changedTouches[0];
281
282	// Synthesise a click event, with an extra attribute so it can be tracked
283	clickEvent = document.createEvent('MouseEvents');
284	clickEvent.initMouseEvent('click', true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
285	clickEvent.forwardedTouchEvent = true;
286	targetElement.dispatchEvent(clickEvent);
287};
288
289
290/**
291 * @param {EventTarget|Element} targetElement
292 */
293FastClick.prototype.focus = function(targetElement) {
294	'use strict';
295	var length;
296
297	if (this.deviceIsIOS && targetElement.setSelectionRange) {
298		length = targetElement.value.length;
299		targetElement.setSelectionRange(length, length);
300	} else {
301		targetElement.focus();
302	}
303};
304
305
306/**
307 * Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
308 *
309 * @param {EventTarget|Element} targetElement
310 */
311FastClick.prototype.updateScrollParent = function(targetElement) {
312	'use strict';
313	var scrollParent, parentElement;
314
315	scrollParent = targetElement.fastClickScrollParent;
316
317	// Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
318	// target element was moved to another parent.
319	if (!scrollParent || !scrollParent.contains(targetElement)) {
320		parentElement = targetElement;
321		do {
322			if (parentElement.scrollHeight > parentElement.offsetHeight) {
323				scrollParent = parentElement;
324				targetElement.fastClickScrollParent = parentElement;
325				break;
326			}
327
328			parentElement = parentElement.parentElement;
329		} while (parentElement);
330	}
331
332	// Always update the scroll top tracker if possible.
333	if (scrollParent) {
334		scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
335	}
336};
337
338
339/**
340 * @param {EventTarget} targetElement
341 * @returns {Element|EventTarget}
342 */
343FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {
344	'use strict';
345
346	// On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
347	if (eventTarget.nodeType === Node.TEXT_NODE) {
348		return eventTarget.parentNode;
349	}
350
351	return eventTarget;
352};
353
354
355/**
356 * On touch start, record the position and scroll offset.
357 *
358 * @param {Event} event
359 * @returns {boolean}
360 */
361FastClick.prototype.onTouchStart = function(event) {
362	'use strict';
363	var targetElement, touch, selection;
364
365	// Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
366	if (event.targetTouches.length > 1) {
367		return true;
368	}
369
370	targetElement = this.getTargetElementFromEventTarget(event.target);
371	touch = event.targetTouches[0];
372
373	if (this.deviceIsIOS) {
374
375		// Only trusted events will deselect text on iOS (issue #49)
376		selection = window.getSelection();
377		if (selection.rangeCount && !selection.isCollapsed) {
378			return true;
379		}
380
381		if (!this.deviceIsIOS4) {
382
383			// Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
384			// when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
385			// with the same identifier as the touch event that previously triggered the click that triggered the alert.
386			// Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
387			// immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
388			if (touch.identifier === this.lastTouchIdentifier) {
389				event.preventDefault();
390				return false;
391			}
392
393			this.lastTouchIdentifier = touch.identifier;
394
395			// If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
396			// 1) the user does a fling scroll on the scrollable layer
397			// 2) the user stops the fling scroll with another tap
398			// then the event.target of the last 'touchend' event will be the element that was under the user's finger
399			// when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
400			// is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
401			this.updateScrollParent(targetElement);
402		}
403	}
404
405	this.trackingClick = true;
406	this.trackingClickStart = event.timeStamp;
407	this.targetElement = targetElement;
408
409	this.touchStartX = touch.pageX;
410	this.touchStartY = touch.pageY;
411
412	// Prevent phantom clicks on fast double-tap (issue #36)
413	if ((event.timeStamp - this.lastClickTime) < 200) {
414		event.preventDefault();
415	}
416
417	return true;
418};
419
420
421/**
422 * Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
423 *
424 * @param {Event} event
425 * @returns {boolean}
426 */
427FastClick.prototype.touchHasMoved = function(event) {
428	'use strict';
429	var touch = event.changedTouches[0], boundary = this.touchBoundary;
430
431	if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
432		return true;
433	}
434
435	return false;
436};
437
438
439/**
440 * Attempt to find the labelled control for the given label element.
441 *
442 * @param {EventTarget|HTMLLabelElement} labelElement
443 * @returns {Element|null}
444 */
445FastClick.prototype.findControl = function(labelElement) {
446	'use strict';
447
448	// Fast path for newer browsers supporting the HTML5 control attribute
449	if (labelElement.control !== undefined) {
450		return labelElement.control;
451	}
452
453	// All browsers under test that support touch events also support the HTML5 htmlFor attribute
454	if (labelElement.htmlFor) {
455		return document.getElementById(labelElement.htmlFor);
456	}
457
458	// If no for attribute exists, attempt to retrieve the first labellable descendant element
459	// the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
460	return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
461};
462
463
464/**
465 * On touch end, determine whether to send a click event at once.
466 *
467 * @param {Event} event
468 * @returns {boolean}
469 */
470FastClick.prototype.onTouchEnd = function(event) {
471	'use strict';
472	var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;
473
474	// If the touch has moved, cancel the click tracking
475	if (this.touchHasMoved(event)) {
476		this.trackingClick = false;
477		this.targetElement = null;
478	}
479
480	if (!this.trackingClick) {
481		return true;
482	}
483
484	// Prevent phantom clicks on fast double-tap (issue #36)
485	if ((event.timeStamp - this.lastClickTime) < 200) {
486		this.cancelNextClick = true;
487		return true;
488	}
489
490	this.lastClickTime = event.timeStamp;
491
492	trackingClickStart = this.trackingClickStart;
493	this.trackingClick = false;
494	this.trackingClickStart = 0;
495
496	// On some iOS devices, the targetElement supplied with the event is invalid if the layer
497	// is performing a transition or scroll, and has to be re-detected manually. Note that
498	// for this to function correctly, it must be called *after* the event target is checked!
499	// See issue #57; also filed as rdar://13048589 .
500	if (this.deviceIsIOSWithBadTarget) {
501		touch = event.changedTouches[0];
502		targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset);
503	}
504
505	targetTagName = targetElement.tagName.toLowerCase();
506	if (targetTagName === 'label') {
507		forElement = this.findControl(targetElement);
508		if (forElement) {
509			this.focus(targetElement);
510			if (this.deviceIsAndroid) {
511				return false;
512			}
513
514			targetElement = forElement;
515		}
516	} else if (this.needsFocus(targetElement)) {
517
518		// Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
519		// Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
520		if ((event.timeStamp - trackingClickStart) > 100 || (this.deviceIsIOS && window.top !== window && targetTagName === 'input')) {
521			this.targetElement = null;
522			return false;
523		}
524
525		this.focus(targetElement);
526
527		// Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
528		if (!this.deviceIsIOS4 || targetTagName !== 'select') {
529			this.targetElement = null;
530			event.preventDefault();
531		}
532
533		return false;
534	}
535
536	if (this.deviceIsIOS && !this.deviceIsIOS4) {
537
538		// Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
539		// and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
540		scrollParent = targetElement.fastClickScrollParent;
541		if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
542			return true;
543		}
544	}
545
546	// Prevent the actual click from going though - unless the target node is marked as requiring
547	// real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
548	if (!this.needsClick(targetElement)) {
549		event.preventDefault();
550		this.sendClick(targetElement, event);
551	}
552
553	return false;
554};
555
556
557/**
558 * On touch cancel, stop tracking the click.
559 *
560 * @returns {void}
561 */
562FastClick.prototype.onTouchCancel = function() {
563	'use strict';
564	this.trackingClick = false;
565	this.targetElement = null;
566};
567
568
569/**
570 * Determine mouse events which should be permitted.
571 *
572 * @param {Event} event
573 * @returns {boolean}
574 */
575FastClick.prototype.onMouse = function(event) {
576	'use strict';
577
578	// If a target element was never set (because a touch event was never fired) allow the event
579	if (!this.targetElement) {
580		return true;
581	}
582
583	if (event.forwardedTouchEvent) {
584		return true;
585	}
586
587	// Programmatically generated events targeting a specific element should be permitted
588	if (!event.cancelable) {
589		return true;
590	}
591
592	// Derive and check the target element to see whether the mouse event needs to be permitted;
593	// unless explicitly enabled, prevent non-touch click events from triggering actions,
594	// to prevent ghost/doubleclicks.
595	if (!this.needsClick(this.targetElement) || this.cancelNextClick) {
596
597		// Prevent any user-added listeners declared on FastClick element from being fired.
598		if (event.stopImmediatePropagation) {
599			event.stopImmediatePropagation();
600		} else {
601
602			// Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
603			event.propagationStopped = true;
604		}
605
606		// Cancel the event
607		event.stopPropagation();
608		event.preventDefault();
609
610		return false;
611	}
612
613	// If the mouse event is permitted, return true for the action to go through.
614	return true;
615};
616
617
618/**
619 * On actual clicks, determine whether this is a touch-generated click, a click action occurring
620 * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
621 * an actual click which should be permitted.
622 *
623 * @param {Event} event
624 * @returns {boolean}
625 */
626FastClick.prototype.onClick = function(event) {
627	'use strict';
628	var permitted;
629
630	// It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to fal
630se and return early. This will cause onTouchEnd to return early.
631	if (this.trackingClick) {
632		this.targetElement = null;
633		this.trackingClick = false;
634		return true;
635	}
636
637	// Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
638	if (event.target.type === 'submit' && event.detail === 0) {
639		return true;
640	}
641
642	permitted = this.onMouse(event);
643
644	// Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
645	if (!permitted) {
646		this.targetElement = null;
647	}
648
649	// If clicks are permitted, return true for the action to go through.
650	return permitted;
651};
652
653
654/**
655 * Remove all FastClick's event listeners.
656 *
657 * @returns {void}
658 */
659FastClick.prototype.destroy = function() {
660	'use strict';
661	var layer = this.layer;
662
663	if (this.deviceIsAndroid) {
664		layer.removeEventListener('mouseover', this.onMouse, true);
665		layer.removeEventListener('mousedown', this.onMouse, true);
666		layer.removeEventListener('mouseup', this.onMouse, true);
667	}
668
669	layer.removeEventListener('click', this.onClick, true);
670	layer.removeEventListener('touchstart', this.onTouchStart, false);
671	layer.removeEventListener('touchend', this.onTouchEnd, false);
672	layer.removeEventListener('touchcancel', this.onTouchCancel, false);
673};
674
675
676/**
677 * Check whether FastClick is needed.
678 *
679 * @param {Element} layer The layer to listen on
680 */
681FastClick.notNeeded = function(layer) {
682	'use strict';
683	var metaViewport;
684
685	// Devices that don't support touch don't need FastClick
686	if (typeof window.ontouchstart === 'undefined') {
687		return true;
688	}
689
690	if ((/Chrome\/[0-9]+/).test(navigator.userAgent)) {
691
692		// Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
693		if (FastClick.prototype.deviceIsAndroid) {
694			metaViewport = document.querySelector('meta[name=viewport]');
695			if (metaViewport && metaViewport.content.indexOf('user-scalable=no') !== -1) {
696				return true;
697			}
698
699		// Chrome desktop doesn't need FastClick (issue #15)
700		} else {
701			return true;
702		}
703	}
704
705	// IE10 with -ms-touch-action: none, which disables double-tap-to-zoom (issue #97)
706	if (layer.style.msTouchAction === 'none') {
707		return true;
708	}
709
710	return false;
711};
712
713
714/**
715 * Factory method for creating a FastClick object
716 *
717 * @param {Element} layer The layer to listen on
718 */
719FastClick.attach = function(layer) {
720	'use strict';
721	return new FastClick(layer);
722};
723
724
725if (typeof define !== 'undefined' && define.amd) {
726
727	// AMD. Register as an anonymous module.
728	define(function() {
729		'use strict';
730		return FastClick;
731	});
732} else if (typeof module !== 'undefined' && module.exports) {
733	module.exports = FastClick.attach;
734	module.exports.FastClick = FastClick;
735} else {
736	window.FastClick = FastClick;
737}

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.