/*! * Tap listener v2.0.0 * listens to taps * MIT license */ /*jshint browser: true, unused: true, undef: true, strict: true */ ( function( window, factory ) { // universal module definition /*jshint strict: false*/ /*globals define, module, require */ if ( typeof define == 'function' && define.amd ) { // AMD define( [ 'unipointer/unipointer' ], function( Unipointer ) { return factory( window, Unipointer ); }); } else if ( typeof module == 'object' && module.exports ) { // CommonJS module.exports = factory( window, require('unipointer') ); } else { // browser global window.TapListener = factory( window, window.Unipointer ); } }( window, function factory( window, Unipointer ) { 'use strict'; // -------------------------- TapListener -------------------------- // function TapListener( elem ) { this.bindTap( elem ); } // inherit Unipointer & EventEmitter var proto = TapListener.prototype = Object.create( Unipointer.prototype ); /** * bind tap event to element * @param {Element} elem */ proto.bindTap = function( elem ) { if ( !elem ) { return; } this.unbindTap(); this.tapElement = elem; this._bindStartEvent( elem, true ); }; proto.unbindTap = function() { if ( !this.tapElement ) { return; } this._bindStartEvent( this.tapElement, false ); delete this.tapElement; }; /** * pointer up * @param {Event} event * @param {Event or Touch} pointer */ proto.pointerUp = function( event, pointer ) { // ignore emulated mouse up clicks if ( this.isIgnoringMouseUp && event.type == 'mouseup' ) { return; } var pointerPoint = Unipointer.getPointerPoint( pointer ); var boundingRect = this.tapElement.getBoundingClientRect(); var scrollX = window.pageXOffset; var scrollY = window.pageYOffset; // calculate if pointer is inside tapElement var isInside = pointerPoint.x >= boundingRect.left + scrollX && pointerPoint.x <= boundingRect.right + scrollX && pointerPoint.y >= boundingRect.top + scrollY && pointerPoint.y <= boundingRect.bottom + scrollY; // trigger callback if pointer is inside element if ( isInside ) { this.emitEvent( 'tap', [ event, pointer ] ); } // set flag for emulated clicks 300ms after touchend if ( event.type != 'mouseup' ) { this.isIgnoringMouseUp = true; // reset flag after 300ms var _this = this; setTimeout( function() { delete _this.isIgnoringMouseUp; }, 400 ); } }; proto.destroy = function() { this.pointerDone(); this.unbindTap(); }; // ----- ----- // return TapListener; }));