An abstraction for working with the mouse.
dd({
event, // Pass original event object in
begin: function (ctx) {
console.log('The beginning');
},
end: function (ctx) {
console.log('The end');
},
move: function (ctx) {
console.log(`Position: x=${ctx.x} y={ctx.y}; distance: dx=${ctx.dx} dy=${ctx.dy}`);
},
});
npm i @vbarbarosh/dd
<script src="https://unpkg.com/@vbarbarosh/dd@1.9.0/dist/dd.js"></script>
This abstraction comes from the following observations:
-
Each interaction with the mouse has the following workflow:
mousedown -> mousemove ... mousemove -> mouseup(here is
context.begin,context.end, andcontext.move). -
Almost always what you are really looking for is how far a mouse was moved from the beginning (here is
context.dxandcontext.dy). -
In general, you have to work with 2 coordinate system: the screen coordinates, and local coordinates. And the only thing you are interested in is your local coordinates. Or, in other words, you have to convert coordinates from screen to local (here is
context.translate).
Pass threshold: n to postpone begin until the pointer travels n
pixels away from the press point. Deltas keep measuring from the original
press point — there is no rebasing at the crossing point — so begin
fires with dx/dy ≈ threshold and a dragged item realigns with the
pointer grip instead of lagging behind by the threshold distance:
dd({
event,
threshold: 5,
begin: function (ctx) {
// First call: ctx.dx/ctx.dy are already ≈ 5
},
});
begin_nothreshold and end_nothreshold handlers run unconditionally at
press and release, even when the threshold was never crossed.
- To drag on touch devices, call
ddfrom apointerdownhandler and settouch-action: noneon the drag handle — otherwise the browser takes over the gesture for scrolling and cancels the pointer. dd.no_pointer_events()disables hit-testing for the whole page, so wheel events stop reaching scrollable containers — skip it when the user should be able to scroll a container mid-drag.IFRAMEandBUTTON[disabled]stops propagation of mouse events. As a resultddwill not callbeginnorupdatehandlers (Events and disabled form fields).