2 * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
5 * @codingstandard ftlabs-jsv2
6 * @copyright The Financial Times Limited [All Rights Reserved]
7 * @license MIT License (see LICENSE.txt)
10 /*jslint browser:true, node:true*/
11 /*global define, Event, Node*/
15 * Instantiate fast-clicking listeners on the specified layer.
18 * @param {Element} layer The layer to listen on
19 * @param {Object} options The options to override the defaults
21 function FastClick(layer
, options
) {
25 options
= options
|| {};
28 * Whether a click is currently being tracked.
32 this.trackingClick
= false;
36 * Timestamp for when click tracking started.
40 this.trackingClickStart
= 0;
44 * The element being tracked for a click.
48 this.targetElement
= null;
52 * X-coordinate of touch start event.
60 * Y-coordinate of touch start event.
68 * ID of the last touch, retrieved from Touch.identifier.
72 this.lastTouchIdentifier
= 0;
76 * Touchmove boundary, beyond which a click will be cancelled.
80 this.touchBoundary
= options
.touchBoundary
|| 10;
84 * The FastClick layer.
91 * The minimum time between tap(touchstart and touchend) events
95 this.tapDelay
= options
.tapDelay
|| 200;
97 if (FastClick
.notNeeded(layer
)) {
101 // Some old versions of Android don't have Function.prototype.bind
102 function bind(method
, context
) {
103 return function() { return method
.apply(context
, arguments
); };
107 var methods
= ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'];
109 for (var i
= 0, l
= methods
.length
; i
< l
; i
++) {
110 context
[methods
[i
]] = bind(context
[methods
[i
]], context
);
113 // Set up event handlers as required
114 if (deviceIsAndroid
) {
115 layer
.addEventListener('mouseover', this.onMouse
, true);
116 layer
.addEventListener('mousedown', this.onMouse
, true);
117 layer
.addEventListener('mouseup', this.onMouse
, true);
120 layer
.addEventListener('click', this.onClick
, true);
121 layer
.addEventListener('touchstart', this.onTouchStart
, false);
122 layer
.addEventListener('touchmove', this.onTouchMove
, false);
123 layer
.addEventListener('touchend', this.onTouchEnd
, false);
124 layer
.addEventListener('touchcancel', this.onTouchCancel
, false);
126 // Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
127 // which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
128 // layer when they are cancelled.
129 if (!Event
.prototype.stopImmediatePropagation
) {
130 layer
.removeEventListener = function(type
, callback
, capture
) {
131 var rmv
= Node
.prototype.removeEventListener
;
132 if (type
=== 'click') {
133 rmv
.call(layer
, type
, callback
.hijacked
|| callback
, capture
);
135 rmv
.call(layer
, type
, callback
, capture
);
139 layer
.addEventListener = function(type
, callback
, capture
) {
140 var adv
= Node
.prototype.addEventListener
;
141 if (type
=== 'click') {
142 adv
.call(layer
, type
, callback
.hijacked
|| (callback
.hijacked = function(event
) {
143 if (!event
.propagationStopped
) {
148 adv
.call(layer
, type
, callback
, capture
);
153 // If a handler is already declared in the element's onclick attribute, it will be fired before
154 // FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
155 // adding it as listener.
156 if (typeof layer
.onclick
=== 'function') {
158 // Android browser on at least 3.2 requires a new reference to the function in layer.onclick
159 // - the old one won't work if passed to addEventListener directly.
160 oldOnClick
= layer
.onclick
;
161 layer
.addEventListener('click', function(event
) {
164 layer
.onclick
= null;
170 * Android requires exceptions.
174 var deviceIsAndroid
= navigator
.userAgent
.indexOf('Android') > 0;
178 * iOS requires exceptions.
182 var deviceIsIOS
= /iP(ad|hone|od)/.test(navigator
.userAgent
);
186 * iOS 4 requires an exception for select elements.
190 var deviceIsIOS4
= deviceIsIOS
&& (/OS 4_\d(_\d)?/).test(navigator
.userAgent
);
194 * iOS 6.0(+?) requires the target element to be manually derived
198 var deviceIsIOSWithBadTarget
= deviceIsIOS
&& (/OS ([6-9]|\d{2})_\d/).test(navigator
.userAgent
);
201 * BlackBerry requires exceptions.
205 var deviceIsBlackBerry10
= navigator
.userAgent
.indexOf('BB10') > 0;
208 * Determine whether a given element requires a native click.
210 * @param {EventTarget|Element} target Target DOM element
211 * @returns {boolean} Returns true if the element needs a native click
213 FastClick
.prototype.needsClick = function(target
) {
215 switch (target
.nodeName
.toLowerCase()) {
217 // Don't send a synthetic click to disabled inputs (issue #62)
221 if (target
.disabled
) {
228 // File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
229 if ((deviceIsIOS
&& target
.type
=== 'file') || target
.disabled
) {
239 return (/\bneedsclick\b/).test(target
.className
);
244 * Determine whether a given element requires a call to focus to simulate click into element.
246 * @param {EventTarget|Element} target Target DOM element
247 * @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
249 FastClick
.prototype.needsFocus = function(target
) {
251 switch (target
.nodeName
.toLowerCase()) {
255 return !deviceIsAndroid
;
257 switch (target
.type
) {
267 // No point in attempting to focus disabled inputs
268 return !target
.disabled
&& !target
.readOnly
;
270 return (/\bneedsfocus\b/).test(target
.className
);
276 * Send a click event to the specified element.
278 * @param {EventTarget|Element} targetElement
279 * @param {Event} event
281 FastClick
.prototype.sendClick = function(targetElement
, event
) {
283 var clickEvent
, touch
;
285 // On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
286 if (document
.activeElement
&& document
.activeElement
!== targetElement
) {
287 document
.activeElement
.blur();
290 touch
= event
.changedTouches
[0];
292 // Synthesise a click event, with an extra attribute so it can be tracked
293 clickEvent
= document
.createEvent('MouseEvents');
294 clickEvent
.initMouseEvent(this.determineEventType(targetElement
), true, true, window
, 1, touch
.screenX
, touch
.screenY
, touch
.clientX
, touch
.clientY
, false, false, false, false, 0, null);
295 clickEvent
.forwardedTouchEvent
= true;
296 targetElement
.dispatchEvent(clickEvent
);
299 FastClick
.prototype.determineEventType = function(targetElement
) {
302 //Issue #159: Android Chrome Select Box does not open with a synthetic click event
303 if (deviceIsAndroid
&& targetElement
.tagName
.toLowerCase() === 'select') {
312 * @param {EventTarget|Element} targetElement
314 FastClick
.prototype.focus = function(targetElement
) {
318 // Issue #160: on iOS 7, some input elements (e.g. date datetime) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
319 if (deviceIsIOS
&& targetElement
.setSelectionRange
&& targetElement
.type
.indexOf('date') !== 0 && targetElement
.type
!== 'time') {
320 length
= targetElement
.value
.length
;
321 targetElement
.setSelectionRange(length
, length
);
323 targetElement
.focus();
329 * Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
331 * @param {EventTarget|Element} targetElement
333 FastClick
.prototype.updateScrollParent = function(targetElement
) {
335 var scrollParent
, parentElement
;
337 scrollParent
= targetElement
.fastClickScrollParent
;
339 // Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
340 // target element was moved to another parent.
341 if (!scrollParent
|| !scrollParent
.contains(targetElement
)) {
342 parentElement
= targetElement
;
344 if (parentElement
.scrollHeight
> parentElement
.offsetHeight
) {
345 scrollParent
= parentElement
;
346 targetElement
.fastClickScrollParent
= parentElement
;
350 parentElement
= parentElement
.parentElement
;
351 } while (parentElement
);
354 // Always update the scroll top tracker if possible.
356 scrollParent
.fastClickLastScrollTop
= scrollParent
.scrollTop
;
362 * @param {EventTarget} targetElement
363 * @returns {Element|EventTarget}
365 FastClick
.prototype.getTargetElementFromEventTarget = function(eventTarget
) {
368 // On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
369 if (eventTarget
.nodeType
=== Node
.TEXT_NODE
) {
370 return eventTarget
.parentNode
;
378 * On touch start, record the position and scroll offset.
380 * @param {Event} event
383 FastClick
.prototype.onTouchStart = function(event
) {
385 var targetElement
, touch
, selection
;
387 // Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
388 if (event
.targetTouches
.length
> 1) {
392 targetElement
= this.getTargetElementFromEventTarget(event
.target
);
393 touch
= event
.targetTouches
[0];
397 // Only trusted events will deselect text on iOS (issue #49)
398 selection
= window
.getSelection();
399 if (selection
.rangeCount
&& !selection
.isCollapsed
) {
405 // Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
406 // when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
407 // with the same identifier as the touch event that previously triggered the click that triggered the alert.
408 // Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
409 // immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
410 if (touch
.identifier
=== this.lastTouchIdentifier
) {
411 event
.preventDefault();
415 this.lastTouchIdentifier
= touch
.identifier
;
417 // If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
418 // 1) the user does a fling scroll on the scrollable layer
419 // 2) the user stops the fling scroll with another tap
420 // then the event.target of the last 'touchend' event will be the element that was under the user's finger
421 // when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
422 // is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
423 this.updateScrollParent(targetElement
);
427 this.trackingClick
= true;
428 this.trackingClickStart
= event
.timeStamp
;
429 this.targetElement
= targetElement
;
431 this.touchStartX
= touch
.pageX
;
432 this.touchStartY
= touch
.pageY
;
434 // Prevent phantom clicks on fast double-tap (issue #36)
435 if ((event
.timeStamp
- this.lastClickTime
) < this.tapDelay
) {
436 event
.preventDefault();
444 * Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
446 * @param {Event} event
449 FastClick
.prototype.touchHasMoved = function(event
) {
451 var touch
= event
.changedTouches
[0], boundary
= this.touchBoundary
;
453 if (Math
.abs(touch
.pageX
- this.touchStartX
) > boundary
|| Math
.abs(touch
.pageY
- this.touchStartY
) > boundary
) {
462 * Update the last position.
464 * @param {Event} event
467 FastClick
.prototype.onTouchMove = function(event
) {
469 if (!this.trackingClick
) {
473 // If the touch has moved, cancel the click tracking
474 if (this.targetElement
!== this.getTargetElementFromEventTarget(event
.target
) || this.touchHasMoved(event
)) {
475 this.trackingClick
= false;
476 this.targetElement
= null;
484 * Attempt to find the labelled control for the given label element.
486 * @param {EventTarget|HTMLLabelElement} labelElement
487 * @returns {Element|null}
489 FastClick
.prototype.findControl = function(labelElement
) {
492 // Fast path for newer browsers supporting the HTML5 control attribute
493 if (labelElement
.control
!== undefined) {
494 return labelElement
.control
;
497 // All browsers under test that support touch events also support the HTML5 htmlFor attribute
498 if (labelElement
.htmlFor
) {
499 return document
.getElementById(labelElement
.htmlFor
);
502 // If no for attribute exists, attempt to retrieve the first labellable descendant element
503 // the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
504 return labelElement
.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
509 * On touch end, determine whether to send a click event at once.
511 * @param {Event} event
514 FastClick
.prototype.onTouchEnd = function(event
) {
516 var forElement
, trackingClickStart
, targetTagName
, scrollParent
, touch
, targetElement
= this.targetElement
;
518 if (!this.trackingClick
) {
522 // Prevent phantom clicks on fast double-tap (issue #36)
523 if ((event
.timeStamp
- this.lastClickTime
) < this.tapDelay
) {
524 this.cancelNextClick
= true;
528 // Reset to prevent wrong click cancel on input (issue #156).
529 this.cancelNextClick
= false;
531 this.lastClickTime
= event
.timeStamp
;
533 trackingClickStart
= this.trackingClickStart
;
534 this.trackingClick
= false;
535 this.trackingClickStart
= 0;
537 // On some iOS devices, the targetElement supplied with the event is invalid if the layer
538 // is performing a transition or scroll, and has to be re-detected manually. Note that
539 // for this to function correctly, it must be called *after* the event target is checked!
540 // See issue #57; also filed as rdar://13048589 .
541 if (deviceIsIOSWithBadTarget
) {
542 touch
= event
.changedTouches
[0];
544 // In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
545 targetElement
= document
.elementFromPoint(touch
.pageX
- window
.pageXOffset
, touch
.pageY
- window
.pageYOffset
) || targetElement
;
546 targetElement
.fastClickScrollParent
= this.targetElement
.fastClickScrollParent
;
549 targetTagName
= targetElement
.tagName
.toLowerCase();
550 if (targetTagName
=== 'label') {
551 forElement
= this.findControl(targetElement
);
553 this.focus(targetElement
);
554 if (deviceIsAndroid
) {
558 targetElement
= forElement
;
560 } else if (this.needsFocus(targetElement
)) {
562 // 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.
563 // 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).
564 if ((event
.timeStamp
- trackingClickStart
) > 100 || (deviceIsIOS
&& window
.top
!== window
&& targetTagName
=== 'input')) {
565 this.targetElement
= null;
569 this.focus(targetElement
);
570 this.sendClick(targetElement
, event
);
572 // Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
573 // Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others)
574 if (!deviceIsIOS
|| targetTagName
!== 'select') {
575 this.targetElement
= null;
576 event
.preventDefault();
582 if (deviceIsIOS
&& !deviceIsIOS4
) {
584 // Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
585 // and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
586 scrollParent
= targetElement
.fastClickScrollParent
;
587 if (scrollParent
&& scrollParent
.fastClickLastScrollTop
!== scrollParent
.scrollTop
) {
592 // Prevent the actual click from going though - unless the target node is marked as requiring
593 // real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
594 if (!this.needsClick(targetElement
)) {
595 event
.preventDefault();
596 this.sendClick(targetElement
, event
);
604 * On touch cancel, stop tracking the click.
608 FastClick
.prototype.onTouchCancel = function() {
610 this.trackingClick
= false;
611 this.targetElement
= null;
616 * Determine mouse events which should be permitted.
618 * @param {Event} event
621 FastClick
.prototype.onMouse = function(event
) {
624 // If a target element was never set (because a touch event was never fired) allow the event
625 if (!this.targetElement
) {
629 if (event
.forwardedTouchEvent
) {
633 // Programmatically generated events targeting a specific element should be permitted
634 if (!event
.cancelable
) {
638 // Derive and check the target element to see whether the mouse event needs to be permitted;
639 // unless explicitly enabled, prevent non-touch click events from triggering actions,
640 // to prevent ghost/doubleclicks.
641 if (!this.needsClick(this.targetElement
) || this.cancelNextClick
) {
643 // Prevent any user-added listeners declared on FastClick element from being fired.
644 if (event
.stopImmediatePropagation
) {
645 event
.stopImmediatePropagation();
648 // Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
649 event
.propagationStopped
= true;
653 event
.stopPropagation();
654 event
.preventDefault();
659 // If the mouse event is permitted, return true for the action to go through.
665 * On actual clicks, determine whether this is a touch-generated click, a click action occurring
666 * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
667 * an actual click which should be permitted.
669 * @param {Event} event
672 FastClick
.prototype.onClick = function(event
) {
676 // 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 false and return early. This will cause onTouchEnd to return early.
677 if (this.trackingClick
) {
678 this.targetElement
= null;
679 this.trackingClick
= false;
683 // 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.
684 if (event
.target
.type
=== 'submit' && event
.detail
=== 0) {
688 permitted
= this.onMouse(event
);
690 // 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.
692 this.targetElement
= null;
695 // If clicks are permitted, return true for the action to go through.
701 * Remove all FastClick's event listeners.
705 FastClick
.prototype.destroy = function() {
707 var layer
= this.layer
;
709 if (deviceIsAndroid
) {
710 layer
.removeEventListener('mouseover', this.onMouse
, true);
711 layer
.removeEventListener('mousedown', this.onMouse
, true);
712 layer
.removeEventListener('mouseup', this.onMouse
, true);
715 layer
.removeEventListener('click', this.onClick
, true);
716 layer
.removeEventListener('touchstart', this.onTouchStart
, false);
717 layer
.removeEventListener('touchmove', this.onTouchMove
, false);
718 layer
.removeEventListener('touchend', this.onTouchEnd
, false);
719 layer
.removeEventListener('touchcancel', this.onTouchCancel
, false);
724 * Check whether FastClick is needed.
726 * @param {Element} layer The layer to listen on
728 FastClick
.notNeeded = function(layer
) {
732 var blackberryVersion
;
734 // Devices that don't support touch don't need FastClick
735 if (typeof window
.ontouchstart
=== 'undefined') {
739 // Chrome version - zero for other browsers
740 chromeVersion
= +(/Chrome\/([0-9]+)/.exec(navigator
.userAgent
) || [,0])[1];
744 if (deviceIsAndroid
) {
745 metaViewport
= document
.querySelector('meta[name=viewport]');
748 // Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
749 if (metaViewport
.content
.indexOf('user-scalable=no') !== -1) {
752 // Chrome 32 and above with width=device-width or less don't need FastClick
753 if (chromeVersion
> 31 && document
.documentElement
.scrollWidth
<= window
.outerWidth
) {
758 // Chrome desktop doesn't need FastClick (issue #15)
764 if (deviceIsBlackBerry10
) {
765 blackberryVersion
= navigator
.userAgent
.match(/Version\/([0-9]*)\.([0-9]*)/);
767 // BlackBerry 10.3+ does not require Fastclick library.
768 // https://github.com/ftlabs/fastclick/issues/251
769 if (blackberryVersion
[1] >= 10 && blackberryVersion
[2] >= 3) {
770 metaViewport
= document
.querySelector('meta[name=viewport]');
773 // user-scalable=no eliminates click delay.
774 if (metaViewport
.content
.indexOf('user-scalable=no') !== -1) {
777 // width=device-width (or less than device-width) eliminates click delay.
778 if (document
.documentElement
.scrollWidth
<= window
.outerWidth
) {
785 // IE10 with -ms-touch-action: none, which disables double-tap-to-zoom (issue #97)
786 if (layer
.style
.msTouchAction
=== 'none') {
795 * Factory method for creating a FastClick object
797 * @param {Element} layer The layer to listen on
798 * @param {Object} options The options to override the defaults
800 FastClick
.attach = function(layer
, options
) {
802 return new FastClick(layer
, options
);
806 if (typeof define
== 'function' && typeof define
.amd
== 'object' && define
.amd
) {
808 // AMD. Register as an anonymous module.
813 } else if (typeof module
!== 'undefined' && module
.exports
) {
814 module
.exports
= FastClick
.attach
;
815 module
.exports
.FastClick
= FastClick
;
817 window
.FastClick
= FastClick
;