High performance, fully cross browser, full featured drag and drop in a tiny (2k gzipped) package


High performance, cross browser, full featured drag and drop in a tiny (2k gzipped) package.



<div id="id"></div>


Using browser globals:

var element = document.getElementById('id');
var options = {
  grid: 10,
  onDragfunction(){ ... }
new Draggable (element, options);

Using AMD/CommonJS:

var Draggable = require ('Draggable');
var element = document.getElementById('id');
new Draggable (element);
  • jQuery or a $-namespaced shim for .on, .off, and .extend (included in the packaged version)
gridNumber0grid size for snapping on drag
filterTargetFunction(target)nullprevent drag when target passes this test
limitElement, Function(x, y, x0, y0), or Object{ x: null, y: null }limit x/y drag bounds
thresholdNumber0threshold before drag begins (in px)
setCursorBoolean (truthy)falsechange cursor to move?
setPositionBoolean (truthy)truechange draggable position to absolute?
smoothDragBoolean (truthy)truesnap to grid only when dropped, not during drag
useGPUBoolean (truthy)truemove graphics calculation/composition to the GPU? (modern browsers only, graceful degradation)
onDragelement, x, y, event
onDragStartelement, x, y, event
onDragEndelement, x, y, event
get---{Object} {x, y}Get the current coordinates
set{Number} x, {Number} yinstanceMove to the specified coordinates
setOption{String} property, {Mixed} valueinstanceSet an option in the live instance
destroy------Unbind the instance's DOM event listeners

Options.limit accepts arguments in several forms:

// no limit 
limit: null
// limit x, but leave y unbounded 
limit: {
  x: [1,10],
  y: null
// limit both axes 
limit: {
  x: [1,10],
  y: [1,500]
// bound x, set y to a constant 
limit: {
  x: [1,10],
  y: 5
// bound with an element 
limit: document.getElementById('id')
// bound with a custom function 
limitfunction (
  x,  // current X coordinate
  y,  // current Y coordinate
  x0, // original X coordinate (where drag was started)
  y0  // original Y coordinate (where drag was started) 
) {
  var radius = 100,
    dx = x - x0,
    dy = y - y0,
    distance = Math.sqrt(dx*dx + dy*dy),
    // only allow dragging within a circle of radius 100 
    outOfRange = distance > radius;
  // if our point is outside of the circle, compute the 
  // point on the circle's edge closest to our point 
  if (outOfRange) {
    x = x0 + radius * (- x0) / distance;
    y = y0 + radius * (- y0) / distance;
  return {
    x: x,
    y: y
  • Chrome 29 on OSX
  • Chrome 28 on Windows
  • Firefox 23 on OSX
  • Firefox 21 on Windows
  • Opera 16 on OSX
  • Safari 6 on OSX
  • Safari 6 on iPhone4/iOS6
  • Safari 6 on iPhone5/iOS6
  • Safari 6 on iPad2/iOS6
  • Safari 6 on iPad3/iOS6
  • Internet Explorer 8-10 on Windows
  • Improve performance on old iOS
  • Unit tests