public
Created

An example implementation on $('selector').tap();

  • Download Gist
jquery.tap.js
JavaScript
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
(function($) {
// DON'T EVER USE AN ALERT INSIDE THE CALLBACK.
$.fn.tap = function(callback) {
if (!this) return false;
 
return this.each(function() {
var element = this;
 
if (element.touchHandler) { return; }
 
element.touchHandler = {
element: element,
callback: callback,
origin: { x: 0, y: 0 },
destination: { x: 0, y: 0 },
threshold: 4,
 
withinThreshold: function(){
// console.debug('destination.x: ' + destination.x + ' destination.y: ' + destination.y)
 
var changeX = this.origin.x - (this.destination.x),
changeY = this.origin.y - (this.destination.y);
 
// console.debug("changeX: " + changeX + " changeY: " + changeY)
 
withinY = changeY < this.threshold && changeY > (this.threshold*-1);
withinX = changeX < this.threshold && changeX > (this.threshold*-1);
 
// console.debug("withinX: " + withinX + " withinY: " + withinY)
 
return withinY || withinX;
},
 
handleEvent: function (e) {
if (e.type == 'touchstart') { this.touchStart(e); }
 
if (e.type == 'touchmove') { this.touchMove(e); }
 
if (e.type == 'touchend') { this.touchEnd(e); }
 
if (e.type == 'touchcancel') { this.touchCancel(e); }
},
 
touchStart: function(event){
// console.debug('touchStart')
this.origin.x = event.targetTouches[0].pageX
this.origin.y = event.targetTouches[0].pageY
 
element.addEventListener('touchmove', this, false);
element.addEventListener('touchend', this, false);
element.addEventListener('touchcancel', this, false);
},
 
touchMove: function(event){
// console.debug('touchMove')
this.destination.x = event.targetTouches[0].pageX
this.destination.y = event.targetTouches[0].pageY
},
 
touchEnd: function(event){
// console.debug('touchEnd')
element.removeEventListener('touchmove', this, false);
element.removeEventListener('touchend', this, false);
element.removeEventListener('touchcancel', this, false);
 
var moved = (!!this.destination.x || !!this.destination.y);
 
// console.debug('moved: ' + moved)
 
if (moved && this.withinThreshold()) {
// console.debug('tapped')
this.callback.apply(this.element, arguments);
}
 
if (!moved) {
// console.debug('tapped');
this.callback.apply(this.element, arguments);
}
 
this.reset();
},
 
touchCancel: function(event){ this.reset(); },
 
reset: function(){
this.origin.x = 0;
this.origin.y = 0;
this.destination.x = 0;
this.destination.y = 0;
}
};
 
element.addEventListener("touchstart", element.touchHandler, false);
});
};
})(jQuery);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.