Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

dragula

bevacqua834kMIT3.7.3TypeScript support: definitely-typed

Drag and drop so simple it hurts

readme

logo.png

Travis CI Dependencies Dev Dependencies Patreon

Drag and drop so simple it hurts

Browser support includes every sane browser and IE7+. (Granted you polyfill the functional Array methods in ES5)

Framework support includes vanilla JavaScript, Angular, and React.

Demo

demo.png

Try out the demo!

Inspiration

Have you ever wanted a drag and drop library that just works? That doesn't just depend on bloated frameworks, that has great support? That actually understands where to place the elements when they are dropped? That doesn't need you to do a zillion things to get it to work? Well, so did I!

Features

  • Super easy to set up
  • No bloated dependencies
  • Figures out sort order on its own
  • A shadow where the item would be dropped offers visual feedback
  • Touch events!
  • Seamlessly handles clicks without any configuration

Install

You can get it on npm.

npm install dragula --save

Or a CDN.

<script src='https://cdnjs.cloudflare.com/ajax/libs/dragula/$VERSION/dragula.min.js'></script>

If you're not using either package manager, you can use dragula by downloading the files in the dist folder. We strongly suggest using npm, though.

Including the JavaScript

There's a caveat to dragula. You shouldn't include it in the <head> of your web applications. It's bad practice to place scripts in the <head>, and as such dragula makes no effort to support this use case.

Place dragula in the <body>, instead.

Including the CSS!

There's a few CSS styles you need to incorporate in order for dragula to work as expected.

You can add them by including dist/dragula.css or dist/dragula.min.css in your document. If you're using Stylus, you can include the styles using the directive below.

@import 'node_modules/dragula/dragula'

Usage

Dragula provides the easiest possible API to make drag and drop a breeze in your applications.

dragula(containers?, options?)

By default, dragula will allow the user to drag an element in any of the containers and drop it in any other container in the list. If the element is dropped anywhere that's not one of the containers, the event will be gracefully cancelled according to the revertOnSpill and removeOnSpill options.

Note that dragging is only triggered on left clicks, and only if no meta keys are pressed.

The example below allows the user to drag elements from left into right, and from right into left.

dragula([document.querySelector('#left'), document.querySelector('#right')]);

You can also provide an options object. Here's an overview of the default values.

dragula(containers, {
  isContainer: function (el) {
    return false; // only elements in drake.containers will be taken into account
  },
  moves: function (el, source, handle, sibling) {
    return true; // elements are always draggable by default
  },
  accepts: function (el, target, source, sibling) {
    return true; // elements can be dropped in any of the `containers` by default
  },
  invalid: function (el, handle) {
    return false; // don't prevent any drags from initiating by default
  },
  direction: 'vertical',             // Y axis is considered when determining where an element would be dropped
  copy: false,                       // elements are moved by default, not copied
  copySortSource: false,             // elements in copy-source containers can be reordered
  revertOnSpill: false,              // spilling will put the element back where it was dragged from, if this is true
  removeOnSpill: false,              // spilling will `.remove` the element, if this is true
  mirrorContainer: document.body,    // set the element that gets mirror elements appended
  ignoreInputTextSelection: true,     // allows users to select input text, see details below
  slideFactorX: 0,               // allows users to select the amount of movement on the X axis before it is considered a drag instead of a click
  slideFactorY: 0,               // allows users to select the amount of movement on the Y axis before it is considered a drag instead of a click
});

You can omit the containers argument and add containers dynamically later on.

var drake = dragula({
  copy: true
});
drake.containers.push(container);

You can also set the containers from the options object.

var drake = dragula({ containers: containers });

And you could also not set any arguments, which defaults to a drake without containers and with the default options.

var drake = dragula();

The options are detailed below.

options.containers

Setting this option is effectively the same as passing the containers in the first argument to dragula(containers, options).

options.isContainer

Besides the containers that you pass to dragula, or the containers you dynamically push or unshift from drake.containers, you can also use this method to specify any sort of logic that defines what is a container for this particular drake instance.

The example below dynamically treats all DOM elements with a CSS class of dragula-container as dragula containers for this drake.

var drake = dragula({
  isContainer: function (el) {
    return el.classList.contains('dragula-container');
  }
});

options.moves

You can define a moves method which will be invoked with (el, source, handle, sibling) whenever an element is clicked. If this method returns false, a drag event won't begin, and the event won't be prevented either. The handle element will be the original click target, which comes in handy to test if that element is an expected "drag handle".

options.accepts

You can set accepts to a method with the following signature: (el, target, source, sibling). It'll be called to make sure that an element el, that came from container source, can be dropped on container target before a sibling element. The sibling can be null, which would mean that the element would be placed as the last element in the container. Note that if options.copy is set to true, el will be set to the copy, instead of the originally dragged element.

Also note that the position where a drag starts is always going to be a valid place where to drop the element, even if accepts returned false for all cases.

options.copy

If copy is set to true (or a method that returns true), items will be copied rather than moved. This implies the following differences:

Event Move Copy
drag Element will be concealed from source Nothing happens
drop Element will be moved into target Element will be cloned into target
remove Element will be removed from DOM Nothing happens
cancel Element will stay in source Nothing happens

If a method is passed, it'll be called whenever an element starts being dragged in order to decide whether it should follow copy behavior or not. Consider the following example.

copy: function (el, source) {
  return el.className === 'you-may-copy-us';
}

options.copySortSource

If copy is set to true (or a method that returns true) and copySortSource is true as well, users will be able to sort elements in copy-source containers.

copy: true,
copySortSource: true

options.revertOnSpill

By default, spilling an element outside of any containers will move the element back to the drop position previewed by the feedback shadow. Setting revertOnSpill to true will ensure elements dropped outside of any approved containers are moved back to the source element where the drag event began, rather than stay at the drop position previewed by the feedback shadow.

options.removeOnSpill

By default, spilling an element outside of any containers will move the element back to the drop position previewed by the feedback shadow. Setting removeOnSpill to true will ensure elements dropped outside of any approved containers are removed from the DOM. Note that remove events won't fire if copy is set to true.

options.direction

When an element is dropped onto a container, it'll be placed near the point where the mouse was released. If the direction is 'vertical', the default value, the Y axis will be considered. Otherwise, if the direction is 'horizontal', the X axis will be considered.

options.invalid

You can provide an invalid method with a (el, handle) signature. This method should return true for elements that shouldn't trigger a drag. The handle argument is the element that was clicked, while el is the item that would be dragged. Here's the default implementation, which doesn't prevent any drags.

function invalidTarget (el, handle) {
  return false;
}

Note that invalid will be invoked on the DOM element that was clicked and every parent up to immediate children of a drake container.

As an example, you could set invalid to return false whenever the clicked element (or any of its parents) is an anchor tag.

invalid: function (el, handle) {
  return el.tagName === 'A';
}

options.mirrorContainer

The DOM element where the mirror element displayed while dragging will be appended to. Defaults to document.body.

options.ignoreInputTextSelection

When this option is enabled, if the user clicks on an input element the drag won't start until their mouse pointer exits the input. This translates into the user being able to select text in inputs contained inside draggable elements, and still drag the element by moving their mouse outside of the input -- so you get the best of both worlds.

This option is enabled by default. Turn it off by setting it to false. If its disabled your users won't be able to select text in inputs within dragula containers with their mouse.

API

The dragula method returns a tiny object with a concise API. We'll refer to the API returned by dragula as drake.

drake.containers

This property contains the collection of containers that was passed to dragula when building this drake instance. You can push more containers and splice old containers at will.

drake.dragging

This property will be true whenever an element is being dragged.

drake.start(item)

Enter drag mode without a shadow. This method is most useful when providing complementary keyboard shortcuts to an existing drag and drop solution. Even though a shadow won't be created at first, the user will get one as soon as they click on item and start dragging it around. Note that if they click and drag something else, .end will be called before picking up the new item.

drake.end()

Gracefully end the drag event as if using the last position marked by the preview shadow as the drop target. The proper cancel or drop event will be fired, depending on whether the item was dropped back where it was originally lifted from (which is essentially a no-op that's treated as a cancel event).

drake.cancel(revert)

If an element managed by drake is currently being dragged, this method will gracefully cancel the drag action. You can also pass in revert at the method invocation level, effectively producing the same result as if revertOnSpill was true.

Note that a "cancellation" will result in a cancel event only in the following scenarios.

  • revertOnSpill is true
  • Drop target (as previewed by the feedback shadow) is the source container and the item is dropped in the same position where it was originally dragged from

drake.remove()

If an element managed by drake is currently being dragged, this method will gracefully remove it from the DOM.

drake.on (Events)

The drake is an event emitter. The following events can be tracked using drake.on(type, listener):

Event Name Listener Arguments Event Description
drag el, source el was lifted from source
dragend el Dragging event for el ended with either cancel, remove, or drop
drop el, target, source, sibling el was dropped into target before a sibling element, and originally came from source
cancel el, container, source el was being dragged but it got nowhere and went back into container, its last stable parent; el originally came from source
remove el, container, source el was being dragged but it got nowhere and it was removed from the DOM. Its last stable parent was container, and originally came from source
shadow el, container, source el, the visual aid shadow, was moved into container. May trigger many times as the position of el changes, even within the same container; el originally came from source
over el, container, source el is over container, and originally came from source
out el, container, source el was dragged out of container or dropped, and originally came from source
cloned clone, original, type DOM element original was cloned as clone, of type ('mirror' or 'copy'). Fired for mirror images and when copy: true

drake.canMove(item)

Returns whether the drake instance can accept drags for a DOM element item. This method returns true when all the conditions outlined below are met, and false otherwise.

  • item is a child of one of the specified containers for drake
  • item passes the pertinent invalid checks
  • item passes a moves check

drake.destroy()

Removes all drag and drop events used by dragula to manage drag and drop between the containers. If .destroy is called while an element is being dragged, the drag will be effectively cancelled.

CSS

Dragula uses only four CSS classes. Their purpose is quickly explained below, but you can check dist/dragula.css to see the corresponding CSS rules.

  • gu-unselectable is added to the mirrorContainer element when dragging. You can use it to style the mirrorContainer while something is being dragged.
  • gu-transit is added to the source element when its mirror image is dragged. It just adds opacity to it.
  • gu-mirror is added to the mirror image. It handles fixed positioning and z-index (and removes any prior margins on the element). Note that the mirror image is appended to the mirrorContainer, not to its initial container. Keep that in mind when styling your elements with nested rules, like .list .item { padding: 10px; }.
  • gu-hide is a helper class to apply display: none to an element.

Contributing

See contributing.markdown for details.

Support

There's now a dedicated support channel in Slack. Visit this page to get an invite. Support requests won't be handled through the repository anymore.

License

MIT

changelog

3.7.3 Up with the times

  • Added ability to set pixel delay in X and Y drag coordinates
  • Bumped `crossvent@1.5.5`
  • Updated all dev dependencies and fixed testing
  • Removed Bower Support

3.7.2 Parental Control

  • Fixed a bug where a missing parent check would cause exceptions

3.7.1 Contrarian Views

3.7.0 Party Like It's the End of the World

  • Added a canMove method that returns whether drake can move a DOM element

3.6.8 Calculated Risk

  • Fixed a bug where drake.cancel would misbehave when copy was true

3.6.7 Miscalculation

  • Fixed a long-standing bug where candidate positioning would be off by one position

3.6.6 Living on the Edge

  • Fixed a bug with clicks on IE7, IE8, IE9

3.6.5 Shadowbane

  • Fixed a bug where shadow even would trigger multiple times when moving over the last position

3.6.4 Water Tap

  • Fixed an instrumentation issue that prevented the tests from running

3.6.3 Body Double

  • Fixed an issue that prevented dragula from execution early in the document load life-cycle

3.6.2 Rugrats

  • Fixed a touch events regression introduced in 3.6.1

3.6.1 Point Blank

  • Fixed issues in touch-enabled browsers such as Windows Phone 10

3.6.0 Prognosis Negative

  • Introduced support for contentEditable DOM attribute

3.5.4 Parental Discretion

  • Switched from .parentElement to .parentNode avoiding bugs when hovering over <svg> elements

3.5.3 Dragster

  • Fixed a bug where mobile devices wouldn't be able to drag elements

3.5.2 Press Start

  • Fixed a bug where <select> inputs couldn't be focused

3.5.1 Which Hunt

  • Fixed a bug when determining the mouse button being pressed
  • Fixed a bug when determining the element behind the mouse cursor when ignoreInputTextSelection was enabled

3.5.0 Input Fanatic

  • Added a feature where users are able to select text ranges with their mouse in inputs within a dragula container

3.4.1 Input Accomodation

  • Fixed a bug where text in inputs inside containers assigned to dragula couldn't be selected

3.4.0 Event Sourcing

  • Events for cancel, remove, and shadow now all provide a source parameter in the third position

3.3.2 Captain Obvious

  • Fixed a bug where out would be emitted with an undefined container

3.3.1 Significant Other

  • Fixed a fringe bug (#207) where the click handler wouldn't work
  • Fixed a bug where drop events would sometimes not receive the current sibling

3.3.0 Brotherhood

  • The options.moves callback now receives a fourth parameter, the sibling found after el
  • The drop event now receives a fourth parameter, the sibling found after el

3.2.0 Sortable Sauce

  • You can now use options.copySortSource to enable sorting in copy-source containers

3.1.0 Copy Paste

  • You can now set options.copy to a method. It'll be invoked once per drag to ask whether the element being dragged should be treated as a copy or not
  • Fixed a bug where starting a drag programatically while an element was being dragged resulted in an exception

3.0.7 Crossroads

  • Fixed a bug in Webpack builds by updating crossvent to 1.5.3

3.0.5 Mouse Rat Rock Band

  • Fixed a bug where mousedown would be prevented and focusing draggable inputs wouldn't be possible

3.0.4 IE is the old IE

  • Fixed a bug in IE8 by updating crossvent to 1.5.2

3.0.3 Forest Fire

  • Fixed a bug in Firefox where dragging links and images would result in issues

3.0.2 Clickhood Rainforest

  • Fixed a historical bug, where click on anchors would be ignored within dragula containers in mobile
  • Fixed a bug where events wouldn't be gracefully removed if drake were destroyed during a drag event
  • Now emits dragend after out to preserve consistency (because drag is emitted before over)
  • Fixed another old bug where attempting to remove elements using removeOnSpill on mobile would fail

3.0.1 Carjacking

  • Fixed a bug in mobile, caused by 3.0.0, where scrolling would be impossible
  • Fixed a bug where dragging would cause text selection in IE8

3.0.0 Guilty Conscience

  • Removed addContainer method, which was previously deprecated
  • Removed removeContainer method, which was previously deprecated
  • Removed delay option in favor of using mousemove
  • Drag events now start on the first occurrence of a mousemove event
  • If mousemove never fires, then the drag machinery won't start, either
  • Changed default value for invalid, now always returns false by default
  • Added mirrorContainer option to determine where the mirror gets appended to (defaults to document.body)

2.1.2 Shady Sibling

  • Fixed a bug where shadow would trigger multiple times while dragging an element over the same spot

2.1.1 Classy Drake

  • Fixed a bug where adding and removing classes might've caused issues on elements that had foreign CSS classes
  • Added an argument to cloned event that specifies the kind of clone. Possible values include mirror and copy at the moment

2.1.0 Over and Out

  • Added over event that fires whenever an element is dragged over a container (or whenever a drag event starts)
  • Added out event that fires whenever an element is dragged out of a container (or whenever a drag event ends)

2.0.7 Mayhem

  • Fixed a bug caused in 2.0.6 where anything would be regarded as a drake container

2.0.6 Coruscant

  • Fixed a bug where isContainer would be called with a el=null in some situations

2.0.5 Cross Ventilation

2.0.4 Transit Overload

  • Set gu-transit after a drag event has fully started

2.0.3 Mice Trap

  • Fixed a bug where using .cancel would throw an exception

2.0.2 Aural Emission

2.0.1 Copycat

  • Fixed a bug where dragging a copy back to origin after hovering over another container would still result in a copy being made if you never spilled the item

2.0.0 Containerization

  • Deprecated addContainer method
  • Deprecated removeContainer method
  • Exposed dragula.containers collection
  • Introduced dynamic isContainer method
  • Can now omit containers argument to dragula(containers, options)
  • Can now pass containers as an option

1.7.0 Clickety Click

  • Differentiate between drag and click using delay option
  • Ability to specify which event targets are invalid drag triggers

1.6.1 Shadow Drake

  • Improved shadow positioning when revertOnSpill is true

1.6.0 Lonely Clown Clone

  • Added 'cloned' event when a DOM element is cloned

1.5.1 Touchypants

  • Fixed an issue where dragula didn't understand where an element was being dropped

1.5.0 Drag Racing

  • Introduced drag handles so that elements could only be dragged from a handle element

1.4.2 Container Camp

  • Fixed a bug where addContainer and removeContainer wouldn't update the list of available containers
  • Fixed a bug where document.body would be accessed before it was available if the scripts were loaded in the <head>

1.4.1 Blood Prince

  • Fixed an issue where manually started drag events wouldn't know if position changed when an item was dropped in the source container
  • Added minor styling to gu-mirror, to visually identify that a drag is in progress

1.4.0 Top Fuel

  • Added a dragend event that's always fired
  • Added a dragging property to API
  • Introduced manual start API method
  • Introduced addContainer and removeContainer dynamic API

1.3.0 Terror

Introduced an .end instance API method that gracefully ends the drag event using the last known valid drop target.

1.2.4 Brother in Arms

  • The accepts option now takes a fourth argument, sibling, giving us a hint of the precise position the item would be dropped in

1.2.3 Breeding Pool

  • Fixed a bug in cross browser behavior that caused the hover effect to ignore scrolling
  • Fixed a bug where touch events weren't working in obscure versions of IE

1.2.2 Originality Accepted

  • Improved accepts mechanism so that it always accepts the original starting point

1.2.1 Firehose

  • Fixed a bug introduced in 1.2.0
  • Fixed a bug where cancelling with revert enabled wouldn't respect sort order

1.2.0 Firefly

  • Introduced moves option, used to determine if an item is draggable
  • Added a source parameter for the drop event
  • Cancelling a drag event when revertOnSpill is true will now move the element to its original position in the source element instead of appending it
  • Fixed a bug where "cancellations" that ended up leaving the dragged element in the source container but changed sort order would trigger a cancel event instead of drop
  • Fixed a bug where "drops" that ended up leaving the element in the exact same place it was dragged from would end up triggering a drop event instead of cancel
  • Added touch event support

1.1.4 Fog Creek

  • Added 'shadow' event to enable easy updates to shadow element as it's moved

1.1.3 Drag Queen

  • Fixed a bug where dragula wouldn't make a copy if the element was dropped outside of a target container
  • If a dragged element gets removed for an instance that has copy set to true, a cancel event is raised instead

1.1.2 Eavesdropping

  • Fixed a bug where "cancellations" that ended up leaving the dragged element somewhere other than the source container wouldn't trigger a drop event

1.1.1 Slipping Jimmy

  • Fixed a bug where the movable shadow wouldn't update properly if the element was hovered over the last position of a container

1.1.0 Age of Shadows

  • Added a movable shadow that gives visual feedback as to where a dragged item would be dropped
  • Added an option to remove dragged elements when they are dropped outside of sanctioned containers
  • Added an option to revert dragged elements back to their source container when they are dropped outside of sanctioned containers

1.0.1 Consuelo

  • Removed console.log statement

1.0.0 IPO

  • Initial Public Release