Created
September 11, 2012 23:19
-
-
Save junosuarez/3702931 to your computer and use it in GitHub Desktop.
Easily support tap events without modifying your click event handlers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*global define: false, window: false */ | |
define(['jquery'], function ($) { | |
'use strict'; | |
return function () { | |
/* Begin monkey-patch Tap event support into $ */ | |
var x = 0, | |
y = 0, | |
threshold = 40, | |
// Sometimes there is lag between the last update and touchend. | |
// Unfortunately, we can't get coords on touchend, so this is | |
// the fudge factor. | |
indexOfTap = function(x, y) { | |
var i, len, tapX, tapY; | |
for(i = 0, len = taps.length; i < len; i++) { | |
tapX = taps[i][0]; | |
tapY = taps[i][1]; | |
if (Math.abs(tapX - x) <= threshold && | |
Math.abs(tapY - y) <= threshold) { | |
return i; | |
} | |
} | |
return -1; | |
}, | |
makeTap = function (callback) { | |
return function (e) { | |
return callback.call(this, e); | |
}; | |
}, | |
wrapClick = function (callback) { | |
return function (e) { | |
var tap = indexOfTap(e.x, e.y); | |
if (tap !== -1) { | |
taps.splice(tap, 1); // remove the tap | |
e.preventDefault(); | |
e.stopPropagation(); | |
return; | |
} | |
return callback.call(this, e); | |
}; | |
}; | |
var taps = []; | |
try { | |
var update = function (e) { | |
x = e.touches[0].clientX; | |
y = e.touches[0].clientY; | |
}; | |
window.addEventListener('touchstart', update, true); | |
window.addEventListener('touchmove', update, true); | |
window.addEventListener('touchend', function (e) { | |
taps.push([x,y]); | |
}, true); | |
} catch (o_O){ | |
//could not register listeners | |
} | |
$.fn.oldBind = $.fn.bind; | |
$.fn.oldDelegate = $.fn.delegate; | |
$.fn.bind = function (event, callback) { | |
if (event.indexOf('click') > -1) { | |
this.oldBind('tap', makeTap(callback)); | |
this.oldBind(event, wrapClick(callback)); | |
} else { | |
this.oldBind(event, callback); | |
} | |
return this; | |
}; | |
$.fn.delegate = function (selector, event, callback) { | |
if (event.indexOf('click') > -1) { | |
this.oldDelegate(selector, 'tap', makeTap(callback)); | |
this.oldDelegate(selector, event, wrapClick(callback)); | |
} else { | |
this.oldDelegate(selector, event, callback); | |
} | |
return this; | |
}; | |
/* end monkey-patch Tap event support into $ */ | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment