Skip to content

Instantly share code, notes, and snippets.

@subhaze
Last active January 23, 2019 16:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save subhaze/a42e48acf376b4576add to your computer and use it in GitHub Desktop.
Save subhaze/a42e48acf376b4576add to your computer and use it in GitHub Desktop.
Probably a more sane way to do this, but, here's a x-device click/tap event; It works with event delegation as well.
jQuery.event.special.tap = {
add: function(handleObj){
var $this = $(this);
var touchMoved = false;
var touched = false;
var touchesHandler = function(e){
if(e.type === 'touchstart'){
touchMoved = false;
touched = true;
}else if(e.type === 'touchmove'){
touchMoved = true;
}else if(e.type === 'touchend'){
if(!touchMoved){
handleObj.handler.call(e.currentTarget, e);
}
setTimeout(function(){
touched = false;
}, 250);
}
};
var clickHandler = function(e){
if(!touched){
handleObj.handler.call(e.currentTarget, e);
}
}
$this.on('touchstart touchmove touchend', handleObj.selector, touchesHandler);
$this.on('click', handleObj.selector, clickHandler);
$this.data('event_special_tap_' + handleObj.guid, {
"click": clickHandler,
"touches": touchesHandler
});
},
remove: function(handleObj){
var $this = $(this);
var handlers = $this.data('event_special_tap_' + handleObj.guid);
$this.off('click', handleObj.selector, handlers.click);
$this.off('touchstart touchmove touchend', handleObj.selector, handlers.touches);
}
};
var tapHandler = function tapHandler(e){
// code ...
};
// will trigger on `click` or `tap`
// `tap` is considered any `touchstart` and `touchend` event
// with no `touchmove` events fired inbetween them
$('.some-selector').on('tap', tapHandler);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment