press
Motion's press
function detects press gestures, firing events when they start, end or cancel.
It's different to native browser events like "pointerstart"
etc in that press
automatically filters out secondary pointer events, like right clicks or a second touch point.
It also expands on "click"
by being great for accessibility. Every element with a press gesture automatically becomes keyboard accessible via focus and the enter key.
press
is also:
Clean: Automatically manages event listeners
Convenient: Accepts either elements or CSS selectors for attaching multiple listeners at once
Lazy: Attaches only the listeners needed
It can be used to fire any function, but also to start and stop animations:
Video overview
Usage
Import
press
can be imported via "motion"
.
Press start
press
can detect press start gestures on either a Element
/array of elements:
It also accepts CSS selectors to detect press start on multiple elements:
The callback is provided the element being pressed, and the triggering PointerEvent
:
Press end
The press start function can optionally return a function that will be called when the press gesture ends:
The press end callback is passed a second argument, info
. It currently has one property, success
. If true
, the press was successfully completed, like a click. If false
, the press ended outside the element.
When using keyboard accessibility, success
will be false
if the element is blurred while the enter key is held.
Cancelling gesture
press
returns a function that, when fired, will cancel all active event handlers associated with the gesture.
Options
passive
Default: true
If set to false
, it'll be possible to call event.preventDefault()
but the gesture will be less performant. Learn more about passive events.
once
Default: false
If set to true
, each provided element will fire their gesture only once.