A tiny (1kb gzipped), high-performance, zero-dependency mouse/touch event wrapper for handling drag interactions. Useful for creating drag and drop interactions or detecting swipes on a touch device.
Inspired by Matt Hinchliffe.
Installation
npm i drag-handler --save
Usage
import { createDragHandler } from 'drag-handler'
// Get a target element
let targetElement = document.getElementById('hasDragEvents');
// Create the handler by passing the element to createDragHandler
let handler = createDragHandler(targetElement);
// Attach event listeners
handler.on('dragstart' (e: CustomEvent<DragGesture>) => {
// Do something at the start of the drag
});
handler.on('drag' (e: CustomEvent<DragGesture>) => {
// Do something during the drag interaction
});
handler.on('dragend' (e: CustomEvent<DragGesture>) => {
// Do something at the end of the drag
});
Handler.on Arguments
Name
Type
Description
eventName
string
The event name to listen for
callback
function
The event listener callback function
Handler Event Names
Name
Description
"dragstart"
Triggered on the initial touchstart/mousedown event
"drag"
Triggered between dragstart and dragend when the pointer position moves
"dragend"
Triggered on the next touchend/mouseup event, when the drag is finished
Handler Event Details
Each handler event will include a DragGesture object as the event details. This object contains several pieces of information about the drag event.