Dragdrop.js
This Javascript package implements drag-n-drop functionality in a browser.
Supports:
- Moving an element horizontally, vertically and in both directions
- Snap to grid functionality
- Limitation of moving distance
- Registering of user-defined function on start, move and stop
Tested in the following browsers: IE 6.0, FF 17, Chrome 22, Safari 5.1.1
Dragdrop.js requires Event.js package, which can be acquired at the following links:
Basic usage
Once initialized, Dradrop.js will apply drag-n-drop functionality to all HTML elements with class="draggable":
var evt = new Event(),
dragdrop = new Dragdrop(evt);
Advanced usage
To implement advanced options an element should be attached to Dragdrop.js, it can be done using set method:
var evt = new Event(),
dragdrop = new Dragdrop(evt),
something = document.getElementById('something');
dragdrop.set(something, {
mode: 0,
minX: 50,
maxX: 350,
minY: 50,
maxY: 350,
snap: 5,
onstart: function(element) {
// do something here
},
onmove: function(element) {
// do something here
},
onstop: function(element) {
// do something here
}
});
which takes 2 arguments, first is the DOM element to be dragged, and the second is the options object which could have the following properties and values:
-
mode (int)
- 0 - move in both directions (default)
- 1 - move horizontally
- 2 - move vertically
- minX (int) - X coordinate limiting the most left position of the element, calculating from 0 (default 0)
- maxX (int) - X coordinate limiting the most right position of the element (default is browser window width)
- minY (int) - Y coordinate limiting the most top position of the element (default 0)
- maxY (int) - Y coordinate limiting the most bottom position of the element (default is browser window height)
- snap (int) - number of pixels to snap the element (default 1)
- onstart - handler for start (mousedown) event
- onmove - handler for move (mousemove) event
- onstop - handler for stop (mouseup) event
All handlers receive DOM node as argument
Some examples:
Move the element:
var evt = new Event(),
dragdrop = new Dragdrop(evt),
horizontal = document.getElementById('horizontal'),
vertical = document.getElementById('vertical'),
hLimited = document.getElementById('horizontal-limited'),
hSnapped = document.getElementById('horizontal-snapped');
dragdrop.set(horizontal, {mode: 1});
dragdrop.set(vertical, {mode: 2});
dragdrop.set(hLimited, {mode: 1, minX: 50, maxX: 250});
dragdrop.set(hSnapped, {mode: 1, snap: 50});
For more examples please refer to demo scripts provided with the package.