Skip to content

Instantly share code, notes, and snippets.

@kalley
Last active December 15, 2015 06:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kalley/5215643 to your computer and use it in GitHub Desktop.
Save kalley/5215643 to your computer and use it in GitHub Desktop.
creates a "press" event that uses clicks for mouses and touchend for touch devices. Current dependencies: jQuery and Modernizr for touch support detection
// jquery.event.press
(function($, Modernizr) {
"use strict";
var touchEnabled = Modernizr && Modernizr.touch;
if ( touchEnabled ) {
// Lift touch properties using fixHooks, inspired by jquery.panzoom, with checks
var touchHook = { props: [ "touches", "targetTouches", "changedTouches", "pageX", "pageY" ] };
$.each([ "touchstart", "touchmove", "touchend" ], function( i, name ) {
var existingHook = $.event.fixHooks[ name ];
if ( ! existingHook ) {
$.event.fixHooks[ name ] = touchHook;
} else {
if ( existingHook.props ) {
existingHook.props = existingHook.props.concat(touchHook.props);
} else {
existingHook.props = touchHook.props;
}
}
});
}
var extendEvent = function(ev, namespace) {
return $.extend({}, ev, {
type: 'press',
namespace: namespace,
pageX: ev.changedTouches ? ev.changedTouches[0].pageX : ev.pageX,
pageY: ev.changedTouches ? ev.changedTouches[0].pageY : ev.pageY
});
};
$.event.special.press = {
add: function(handleObj) {
var threshold = ( handleObj.data && handleObj.data.threshold ) || 6;
var namespace = 'press' + ( handleObj.namespace ? '.' + handleObj.namespace : '' );
var selector = handleObj.selector;
var el = $(this);
if ( touchEnabled ) {
el.on('touchstart.' + namespace, selector, function(ev) {
var canClick = true;
var startX = ev.pageX;
var startY = ev.pageY;
el.on('touchmove.' + namespace, selector, function(ev) {
var deltaX = startX - ev.pageX;
var deltaY = startY - ev.pageY;
if ( ( deltaX * deltaX ) + ( deltaY * deltaY ) > ( threshold * threshold ) ) {
canClick = false;
}
}).on('touchend.' + namespace, selector, function(ev) {
if ( canClick ) {
var event = extendEvent(ev, handleObj.namespace);
$(this).trigger(event).off('touchmove.' + namespace + ' touchend.' + namespace);
}
canClick = true;
});
});
} else {
el.on('click.' + namespace, selector, function(ev) {
var event = extendEvent(ev, handleObj.namespace);
ev.stopPropagation();
$(this).trigger(event);
});
}
},
remove: function(handleObj) {
var namespace = handleObj.namespace ? '.' + handleObj.namespace : '';
$(this).off('.press' + namespace, handleObj.selector);
}
};
})(jQuery, Modernizr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment