Skip to content
/ drag Public

🏄 A lightweight JavaScript "hold and drag" utility. Vanilla JS - No dependencies.

License

Notifications You must be signed in to change notification settings

mystroken/drag

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

49 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🏄 drag

npm bundle size npm npm GitHub last commit contributions welcome GitHub stars Tweet

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🔥🔥



Usage

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);
}


Options

listener

Determines the DOM element on which to apply the hold and drag feature.

Default Type
window DOM Element

multiplier

Set a speed multiplier for the movement (the normal speed is 1).

Default Type
1 int


Methods

on(callback)

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

off(callback)

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

About

🏄 A lightweight JavaScript "hold and drag" utility. Vanilla JS - No dependencies.

Topics

Resources

License

Security policy

Stars

Watchers

Forks

Packages

No packages published