Skip to content

Instantly share code, notes, and snippets.

@kosich
Last active July 10, 2019 03:37
Show Gist options
  • Save kosich/23188dd86633b6c2efb7 to your computer and use it in GitHub Desktop.
Save kosich/23188dd86633b6c2efb7 to your computer and use it in GitHub Desktop.

this approach is based not on blocking some square on the screen, but rather blocking events from other device (after touch interaction mouse events are blocked for some period and vice versa)

note: its a draft for angular-hammer use, so one would need to modify it a little to use with native elements ( atm it accepts jQuery element and addresses dom via element[0] )

var ANTI_GHOST_DELAY = 2000;
var POINTER_TYPE = {
MOUSE: 0,
TOUCH: 1
};
function preventGhosts(element) {
var latestInteractionType,
latestInteractionTime;
function handleTap(type, e) {
// console.log('got tap ' + e.type + ' of pointer ' + type);
var now = Date.now();
if (type !== latestInteractionType) {
if (now - latestInteractionTime <= ANTI_GHOST_DELAY) {
// console.log('!prevented!');
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
}
latestInteractionType = type;
}
latestInteractionTime = now;
}
function attachEvents(eventList, interactionType) {
eventList.forEach(function(eventName) {
element[0].addEventListener(eventName, handleTap.bind(null, interactionType), true);
});
}
var mouseEvents = ['mousedown', 'mouseup', 'mousemove'];
var touchEvents = ['touchstart', 'touchend'];
attachEvents(mouseEvents, POINTER_TYPE.MOUSE);
attachEvents(touchEvents, POINTER_TYPE.TOUCH);
}
@googabeast
Copy link

Clean and I like it, here is the iteration I did that uses pure JQuery objects as the reference.

https://jsfiddle.net/googabeast/ggsqxcms/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment