A lightweight JavaScript "hold and drag" utility. Vanilla JS - No dependencies.
Its size is ~867 Bytes (minified and compressed).
➝ See the online demo (Advanced example) | Demo Source Code🔥🔥
npm install @mystroken/drag
and start using the hold and drag system.
import Drag from '@mystroken/drag';
// Elements to listen/move.
const slidable = document.querySelector('#slidable');
const container = document.querySelector('#container');
// Where to store the drag position.
let currentX = 0;
let currentY = 0;
// Initialize the library.
const options = {
listener: container,
multiplier: 2
};
const drag = new Drag(options);
// Store the cursor position on move.
drag.on(event => {
currentX = event.X;
currentY = event.Y;
});
// Use the cursor position to slide the slidable element.
requestAnimationFrame(move);
function move() {
slidable.style.transform = `translate3d(${currentX}px, ${currentY}px, 0px)`;
requestAnimationFrame(move);
}
Determines the DOM element on which to apply the hold and drag feature.
Default | Type |
---|---|
window |
DOM Element |
Set a speed multiplier for the movement (the normal speed is 1).
Default | Type |
---|---|
1 |
int |
Subscribes a callback function to listen any "hold and drag" operation.
drag.on(function(event) {
// Start consuming the event data.
currentX = event.X;
currentY = event.Y;
});
Argument | Type | Params | Required |
---|---|---|---|
callback | Function |
An event object giving the current X & Y positions of the mouse on the container | Yes |
Unsubscribes the callback function from listening operations.
Argument | Type | Params | Required |
---|---|---|---|
callback | Function |
An event object giving the current X & Y positions of the mouse on the container | Yes |