Skip to content

Instantly share code, notes, and snippets.

@nihlton
Created October 25, 2020 03:51
Show Gist options
  • Save nihlton/cfeb311119998c075e1fbc48c4dba1dc to your computer and use it in GitHub Desktop.
Save nihlton/cfeb311119998c075e1fbc48c4dba1dc to your computer and use it in GitHub Desktop.
long Press hook-like
export default function longPressEvents(callback, ms = 500) {
let timeout = null
const start = () => (timeout = setTimeout(callback, ms))
const stop = () => timeout && window.clearTimeout(timeout)
return callback ? {
onMouseDown: start,
onMouseUp: stop,
onMouseLeave: stop,
onTouchStart: start,
onTouchMove: stop,
onTouchEnd: stop,
} : {}
}
@nihlton
Copy link
Author

nihlton commented Oct 25, 2020

I've seen useLongPress hooks floating around. they aren't great, since you have to call hooks from the main function body.

can't do stuff like this:
items.map(item => <button {...useLongPress(handleClick)}>{item}</button>)

this simple vanilla JS side steps the limitations of hooks.

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