source: main/trunk/model-interfaces-dev/heritage-nz/iframe/heritage-nz-dl_files/fastclick.js@ 32796

Last change on this file since 32796 was 32796, checked in by davidb, 5 years ago

Initial set of files to provide look and feel of Heritage NZ site, plus SVN clickable map in an iframe

  • Property svn:executable set to *
File size: 24.8 KB
Line 
1/**
2 * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
3 *
4 * @version 1.0.0
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;
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 (FastClick.notNeeded(layer)) {
89 return;
90 }
91
92 // Some old versions of Android don't have Function.prototype.bind
93 function bind(method, context) {
94 return function () { return method.apply(context, arguments); };
95 }
96
97 // Set up event handlers as required
98 if (deviceIsAndroid) {
99 layer.addEventListener('mouseover', bind(this.onMouse, this), true);
100 layer.addEventListener('mousedown', bind(this.onMouse, this), true);
101 layer.addEventListener('mouseup', bind(this.onMouse, this), true);
102 }
103
104 layer.addEventListener('click', bind(this.onClick, this), true);
105 layer.addEventListener('touchstart', bind(this.onTouchStart, this), false);
106 layer.addEventListener('touchmove', bind(this.onTouchMove, this), false);
107 layer.addEventListener('touchend', bind(this.onTouchEnd, this), false);
108 layer.addEventListener('touchcancel', bind(this.onTouchCancel, this), false);
109
110 // Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
111 // which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
112 // layer when they are cancelled.
113 if (!Event.prototype.stopImmediatePropagation) {
114 layer.removeEventListener = function (type, callback, capture) {
115 var rmv = Node.prototype.removeEventListener;
116 if (type === 'click') {
117 rmv.call(layer, type, callback.hijacked || callback, capture);
118 } else {
119 rmv.call(layer, type, callback, capture);
120 }
121 };
122
123 layer.addEventListener = function (type, callback, capture) {
124 var adv = Node.prototype.addEventListener;
125 if (type === 'click') {
126 adv.call(layer, type, callback.hijacked || (callback.hijacked = function (event) {
127 if (!event.propagationStopped) {
128 callback(event);
129 }
130 }), capture);
131 } else {
132 adv.call(layer, type, callback, capture);
133 }
134 };
135 }
136
137 // If a handler is already declared in the element's onclick attribute, it will be fired before
138 // FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
139 // adding it as listener.
140 if (typeof layer.onclick === 'function') {
141
142 // Android browser on at least 3.2 requires a new reference to the function in layer.onclick
143 // - the old one won't work if passed to addEventListener directly.
144 oldOnClick = layer.onclick;
145 layer.addEventListener('click', function (event) {
146 oldOnClick(event);
147 }, false);
148 layer.onclick = null;
149 }
150}
151
152
153/**
154 * Android requires exceptions.
155 *
156 * @type boolean
157 */
158var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0;
159
160
161/**
162 * iOS requires exceptions.
163 *
164 * @type boolean
165 */
166var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent);
167
168
169/**
170 * iOS 4 requires an exception for select elements.
171 *
172 * @type boolean
173 */
174var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);
175
176
177/**
178 * iOS 6.0(+?) requires the target element to be manually derived
179 *
180 * @type boolean
181 */
182var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS ([6-9]|\d{2})_\d/).test(navigator.userAgent);
183
184
185/**
186 * Determine whether a given element requires a native click.
187 *
188 * @param {EventTarget|Element} target Target DOM element
189 * @returns {boolean} Returns true if the element needs a native click
190 */
191FastClick.prototype.needsClick = function (target) {
192 'use strict';
193 switch (target.nodeName.toLowerCase()) {
194
195 // Don't send a synthetic click to disabled inputs (issue #62)
196 case 'button':
197 case 'select':
198 case 'textarea':
199 if (target.disabled) {
200 return true;
201 }
202
203 break;
204 case 'input':
205
206 // File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
207 if ((deviceIsIOS && target.type === 'file') || target.disabled) {
208 return true;
209 }
210
211 break;
212 case 'label':
213 case 'video':
214 return true;
215 }
216
217 return (/\bneedsclick\b/).test(target.className);
218};
219
220
221/**
222 * Determine whether a given element requires a call to focus to simulate click into element.
223 *
224 * @param {EventTarget|Element} target Target DOM element
225 * @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
226 */
227FastClick.prototype.needsFocus = function (target) {
228 'use strict';
229 switch (target.nodeName.toLowerCase()) {
230 case 'textarea':
231 return true;
232 case 'select':
233 return !deviceIsAndroid;
234 case 'input':
235 switch (target.type) {
236 case 'button':
237 case 'checkbox':
238 case 'file':
239 case 'image':
240 case 'radio':
241 case 'submit':
242 return false;
243 }
244
245 // No point in attempting to focus disabled inputs
246 return !target.disabled && !target.readOnly;
247 default:
248 return (/\bneedsfocus\b/).test(target.className);
249 }
250};
251
252
253/**
254 * Send a click event to the specified element.
255 *
256 * @param {EventTarget|Element} targetElement
257 * @param {Event} event
258 */
259FastClick.prototype.sendClick = function (targetElement, event) {
260 'use strict';
261 var clickEvent, touch;
262
263 // On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
264 if (document.activeElement && document.activeElement !== targetElement) {
265 document.activeElement.blur();
266 }
267
268 touch = event.changedTouches[0];
269
270 // Synthesise a click event, with an extra attribute so it can be tracked
271 clickEvent = document.createEvent('MouseEvents');
272 clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
273 clickEvent.forwardedTouchEvent = true;
274 targetElement.dispatchEvent(clickEvent);
275};
276
277FastClick.prototype.determineEventType = function (targetElement) {
278 'use strict';
279
280 //Issue #159: Android Chrome Select Box does not open with a synthetic click event
281 if (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') {
282 return 'mousedown';
283 }
284
285 return 'click';
286};
287
288
289/**
290 * @param {EventTarget|Element} targetElement
291 */
292FastClick.prototype.focus = function (targetElement) {
293 'use strict';
294 var length;
295
296 // 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.
297 if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time') {
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 (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 (!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 * Update the last position.
441 *
442 * @param {Event} event
443 * @returns {boolean}
444 */
445FastClick.prototype.onTouchMove = function (event) {
446 'use strict';
447 if (!this.trackingClick) {
448 return true;
449 }
450
451 // If the touch has moved, cancel the click tracking
452 if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
453 this.trackingClick = false;
454 this.targetElement = null;
455 }
456
457 return true;
458};
459
460
461/**
462 * Attempt to find the labelled control for the given label element.
463 *
464 * @param {EventTarget|HTMLLabelElement} labelElement
465 * @returns {Element|null}
466 */
467FastClick.prototype.findControl = function (labelElement) {
468 'use strict';
469
470 // Fast path for newer browsers supporting the HTML5 control attribute
471 if (labelElement.control !== undefined) {
472 return labelElement.control;
473 }
474
475 // All browsers under test that support touch events also support the HTML5 htmlFor attribute
476 if (labelElement.htmlFor) {
477 return document.getElementById(labelElement.htmlFor);
478 }
479
480 // If no for attribute exists, attempt to retrieve the first labellable descendant element
481 // the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
482 return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
483};
484
485
486/**
487 * On touch end, determine whether to send a click event at once.
488 *
489 * @param {Event} event
490 * @returns {boolean}
491 */
492FastClick.prototype.onTouchEnd = function (event) {
493 'use strict';
494 var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;
495
496 if (!this.trackingClick) {
497 return true;
498 }
499
500 // Prevent phantom clicks on fast double-tap (issue #36)
501 if ((event.timeStamp - this.lastClickTime) < 200) {
502 this.cancelNextClick = true;
503 return true;
504 }
505
506 // Reset to prevent wrong click cancel on input (issue #156).
507 this.cancelNextClick = false;
508
509 this.lastClickTime = event.timeStamp;
510
511 trackingClickStart = this.trackingClickStart;
512 this.trackingClick = false;
513 this.trackingClickStart = 0;
514
515 // On some iOS devices, the targetElement supplied with the event is invalid if the layer
516 // is performing a transition or scroll, and has to be re-detected manually. Note that
517 // for this to function correctly, it must be called *after* the event target is checked!
518 // See issue #57; also filed as rdar://13048589 .
519 if (deviceIsIOSWithBadTarget) {
520 touch = event.changedTouches[0];
521
522 // In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
523 targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
524 targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
525 }
526
527 targetTagName = targetElement.tagName.toLowerCase();
528 if (targetTagName === 'label') {
529 forElement = this.findControl(targetElement);
530 if (forElement) {
531 this.focus(targetElement);
532 if (deviceIsAndroid) {
533 return false;
534 }
535
536 targetElement = forElement;
537 }
538 } else if (this.needsFocus(targetElement)) {
539
540 // 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.
541 // 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).
542 if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) {
543 this.targetElement = null;
544 return false;
545 }
546
547 this.focus(targetElement);
548 this.sendClick(targetElement, event);
549
550 // Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
551 if (!deviceIsIOS4 || targetTagName !== 'select') {
552 this.targetElement = null;
553 event.preventDefault();
554 }
555
556 return false;
557 }
558
559 if (deviceIsIOS && !deviceIsIOS4) {
560
561 // Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
562 // and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
563 scrollParent = targetElement.fastClickScrollParent;
564 if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
565 return true;
566 }
567 }
568
569 // Prevent the actual click from going though - unless the target node is marked as requiring
570 // real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
571 if (!this.needsClick(targetElement)) {
572 event.preventDefault();
573 this.sendClick(targetElement, event);
574 }
575
576 return false;
577};
578
579
580/**
581 * On touch cancel, stop tracking the click.
582 *
583 * @returns {void}
584 */
585FastClick.prototype.onTouchCancel = function () {
586 'use strict';
587 this.trackingClick = false;
588 this.targetElement = null;
589};
590
591
592/**
593 * Determine mouse events which should be permitted.
594 *
595 * @param {Event} event
596 * @returns {boolean}
597 */
598FastClick.prototype.onMouse = function (event) {
599 'use strict';
600
601 // If a target element was never set (because a touch event was never fired) allow the event
602 if (!this.targetElement) {
603 return true;
604 }
605
606 if (event.forwardedTouchEvent) {
607 return true;
608 }
609
610 // Programmatically generated events targeting a specific element should be permitted
611 if (!event.cancelable) {
612 return true;
613 }
614
615 // Derive and check the target element to see whether the mouse event needs to be permitted;
616 // unless explicitly enabled, prevent non-touch click events from triggering actions,
617 // to prevent ghost/doubleclicks.
618 if (!this.needsClick(this.targetElement) || this.cancelNextClick) {
619
620 // Prevent any user-added listeners declared on FastClick element from being fired.
621 if (event.stopImmediatePropagation) {
622 event.stopImmediatePropagation();
623 } else {
624
625 // Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
626 event.propagationStopped = true;
627 }
628
629 // Cancel the event
630 event.stopPropagation();
631 event.preventDefault();
632
633 return false;
634 }
635
636 // If the mouse event is permitted, return true for the action to go through.
637 return true;
638};
639
640
641/**
642 * On actual clicks, determine whether this is a touch-generated click, a click action occurring
643 * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
644 * an actual click which should be permitted.
645 *
646 * @param {Event} event
647 * @returns {boolean}
648 */
649FastClick.prototype.onClick = function (event) {
650 'use strict';
651 var permitted;
652
653 // 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.
654 if (this.trackingClick) {
655 this.targetElement = null;
656 this.trackingClick = false;
657 return true;
658 }
659
660 // 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.
661 if (event.target.type === 'submit' && event.detail === 0) {
662 return true;
663 }
664
665 permitted = this.onMouse(event);
666
667 // 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.
668 if (!permitted) {
669 this.targetElement = null;
670 }
671
672 // If clicks are permitted, return true for the action to go through.
673 return permitted;
674};
675
676
677/**
678 * Remove all FastClick's event listeners.
679 *
680 * @returns {void}
681 */
682FastClick.prototype.destroy = function () {
683 'use strict';
684 var layer = this.layer;
685
686 if (deviceIsAndroid) {
687 layer.removeEventListener('mouseover', this.onMouse, true);
688 layer.removeEventListener('mousedown', this.onMouse, true);
689 layer.removeEventListener('mouseup', this.onMouse, true);
690 }
691
692 layer.removeEventListener('click', this.onClick, true);
693 layer.removeEventListener('touchstart', this.onTouchStart, false);
694 layer.removeEventListener('touchmove', this.onTouchMove, false);
695 layer.removeEventListener('touchend', this.onTouchEnd, false);
696 layer.removeEventListener('touchcancel', this.onTouchCancel, false);
697};
698
699
700/**
701 * Check whether FastClick is needed.
702 *
703 * @param {Element} layer The layer to listen on
704 */
705FastClick.notNeeded = function (layer) {
706 'use strict';
707 var metaViewport;
708 var chromeVersion;
709
710 // Devices that don't support touch don't need FastClick
711 if (typeof window.ontouchstart === 'undefined') {
712 return true;
713 }
714
715 // Chrome version - zero for other browsers
716 chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [, 0])[1];
717
718 if (chromeVersion) {
719
720 if (deviceIsAndroid) {
721 metaViewport = document.querySelector('meta[name=viewport]');
722
723 if (metaViewport) {
724 // Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
725 if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
726 return true;
727 }
728 // Chrome 32 and above with width=device-width or less don't need FastClick
729 if (chromeVersion > 31 && window.innerWidth <= window.screen.width) {
730 return true;
731 }
732 }
733
734 // Chrome desktop doesn't need FastClick (issue #15)
735 } else {
736 return true;
737 }
738 }
739
740 // IE10 with -ms-touch-action: none, which disables double-tap-to-zoom (issue #97)
741 if (layer.style.msTouchAction === 'none') {
742 return true;
743 }
744
745 return false;
746};
747
748
749/**
750 * Factory method for creating a FastClick object
751 *
752 * @param {Element} layer The layer to listen on
753 */
754FastClick.attach = function (layer) {
755 'use strict';
756 return new FastClick(layer);
757};
758
759
760if (typeof define !== 'undefined' && define.amd) {
761
762 // AMD. Register as an anonymous module.
763 define(function () {
764 'use strict';
765 return FastClick;
766 });
767} else if (typeof module !== 'undefined' && module.exports) {
768 module.exports = FastClick.attach;
769 module.exports.FastClick = FastClick;
770} else {
771 window.FastClick = FastClick;
772}
Note: See TracBrowser for help on using the repository browser.