Skip to content

onPointerIntent

Tells a tap from a drag, and hover from touch, on one element: the pointer-event logic every draggable or clickable widget rewrites. Press, then either release within threshold pixels (onTap) or move past it (onDragStart, onDrag…, onDragEnd).

Only the first pointer that presses is followed (multi-touch ignores the others), and it is captured with setPointerCapture so a drag keeps going outside the element — which means the element receives the pointerup even when released elsewhere. Without pointer events (no addEventListener on target), it does nothing and returns a function that does nothing.

Available since v3.1.8

import { onPointerIntent } from '@helpers4/browser';
// or, from the all-in-one package (same code, one install):
import { onPointerIntent } from 'helpers4/browser';
onPointerIntent(target: Element, handlers: PointerIntentHandlers, options: PointerIntentOptions): function
ParameterTypeDescription
targetElementThe element to listen on
handlersPointerIntentHandlersWhat to do for each intent — see PointerIntentHandlers
optionsPointerIntentOptionsThreshold, button and cancellation — see PointerIntentOptions

function — A function that stops listening

A press released within the threshold is a tap; moving past it starts a drag.

const stop = onPointerIntent(handle, {
  onTap: () => select(),
  onDrag: ({ dx, dy }) => move(dx, dy),
});
stop();

One abort() removes the listeners, as on unmount.

const controller = new AbortController();
onPointerIntent(handle, { onPress }, { signal: controller.signal });
controller.abort();

What a pointer is doing, passed to the handlers of onPointerIntent.

interface PointerIntent {
  dx: number;
  dy: number;
  event: PointerEvent;
  startX: number;
  startY: number;
  x: number;
  y: number;
}

Handlers for onPointerIntent; every one is optional.

interface PointerIntentHandlers {
  onCancel?: function;
  onDrag?: function;
  onDragEnd?: function;
  onDragStart?: function;
  onHover?: function;
  onPress?: function;
  onTap?: function;
}

Options for onPointerIntent.

interface PointerIntentOptions {
  button?: number;
  signal?: AbortSignalLike;
  threshold?: number;
}

View source on GitHub