Skip to content

Instantly share code, notes, and snippets.

@davidhellsing
Last active August 29, 2015 13:57
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 davidhellsing/9484466 to your computer and use it in GitHub Desktop.
Save davidhellsing/9484466 to your computer and use it in GitHub Desktop.
click:fast - a fast click event alternative that triggers the handler much faster on touch devices (and also prevents click events on swipe/scroll).
$.event.special['click:fast'] = {
propagate: true,
add: function(handleObj) {
var getCoords = function(e) {
if ( e.touches && e.touches.length ) {
var touch = e.touches[0];
return {
x: touch.pageX,
y: touch.pageY
};
}
};
var def = {
touched: false,
touchdown: false,
coords: { x:0, y:0 },
evObj: {}
};
$(this).data({
clickstate: def,
timer: 0
}).on('touchstart.fast', function(e) {
window.clearTimeout($(this).data('timer'));
$(this).data('clickstate', {
touched: true,
touchdown: true,
coords: getCoords(e.originalEvent),
evObj: e
});
}).on('touchmove.fast', function(e) {
var coords = getCoords(e.originalEvent),
state = $(this).data('clickstate'),
distance = Math.max(
Math.abs(state.coords.x - coords.x),
Math.abs(state.coords.y - coords.y)
);
if ( distance > 6 ) {
$(this).data('clickstate', $.extend(state, {
touchdown: false
}));
}
}).on('touchend.fast', function(e) {
var $this = $(this),
state = $this.data('clickstate');
if(state.touchdown) {
handleObj.handler.call(this, e);
}
$this.data('timer', window.setTimeout(function() {
$this.data('clickstate', def);
}, 400));
}).on('click.fast', function(e) {
var state = $(this).data('clickstate');
if ( state.touched ) {
return false;
}
$(this).data('clickstate', def);
handleObj.handler.call(this, e);
});
},
remove: function() {
$(this).off('touchstart.fast touchmove.fast touchend.fast click.fast');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment