Skip to content

Instantly share code, notes, and snippets.

@bozdoz
Last active February 26, 2021 03:39
Show Gist options
  • Save bozdoz/000c6335af28717796644d3912b70de0 to your computer and use it in GitHub Desktop.
Save bozdoz/000c6335af28717796644d3912b70de0 to your computer and use it in GitHub Desktop.
Add mobile equivalent for contextmenu event; User touches element for a given length of time
/**
* Add mobile equivalent for contextmenu event.
* User touches element for a given length of time
*/
const addLongTouch = (
elem: HTMLElement,
callback: (event: TouchEvent) => void,
delay = 650
): (() => void) => {
let timeout: number;
const clear = () => {
window.clearTimeout(timeout);
timeout = 0;
};
const onTouchStart = (e: TouchEvent) => {
if (e.touches.length === 1) {
timeout = window.setTimeout(() => callback(e), delay);
} else if (timeout) {
// clear on multiple touches
clear();
}
};
elem.addEventListener('touchstart', onTouchStart);
elem.addEventListener('touchmove', clear);
elem.addEventListener('touchend', clear);
return () => {
elem.removeEventListener('touchstart', onTouchStart);
elem.removeEventListener('touchmove', clear);
elem.removeEventListener('touchend', clear);
};
};
export default addLongTouch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment