:ok_hand: Drag and drop so simple it hurts

Overview

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

We have a dedicated support channel in Slack. See this issue to get an invite. Support requests won't be handled through the repository.

License

MIT

Comments
  • Add scrolling support vertically and horizontally

    Add scrolling support vertically and horizontally

    This PR will be addressing these drag and scrolling issues: https://github.com/bevacqua/dragula/issues/327, https://github.com/bevacqua/dragula/issues/121.

    TODOS:

    • [x] Add support scrolling containers
    • [x] Add support for horizontal scrolling
    • [x] Allow auto scrolling at scroll edge
    • [x] Add touch support
    opened by nguyenj 49
  • Scroll while dragging

    Scroll while dragging

    I see two situations where implementing some scrolling would be very helpful -

    If the container is taller than the viewport. It would be nice if the plugin could scroll the page when you hit the edge of the viewport while dragging an item.

    If the target container has a height restriction along with overflow:scroll. Similarly, the plugin could change the scroll position of the target container when you hit an edge.

    I made an attempt at implementing this but it seems that my handler bound to mousemove was only being triggered when I dragged an element outside of the container and back in. I'm not sure if the plugin is killing mousemove events for performance reasons (that's my guess) but is there any other way to get the position of the dragged element as it moves?

    Thanks!

    bug help-wanted 
    opened by bryannielsen 27
  • `accepts` is never called on iOS 8.4.1

    `accepts` is never called on iOS 8.4.1

    We're using Dragula JS in a hybrid mobile app. We noticed that after upgrading to the latest iOS version earlier (8.4.1), dragging doesn't work as it previously did.

    Dragging an item starts ok but the 'accepts' callback is never triggered because getElementBehindPoint() seems to always return the whole document, not the specific element behind the point. This means that dropping isn't possible.

    Of course, this is probably more of an iOS issue than a Dragula one, but I thought it worth mentioning here in case others have the same problem, or there may be a workaround or known fix?

    support minor-bug 
    opened by Bushjumper 24
  • Licensing: Switch to GPLv3?

    Licensing: Switch to GPLv3?

    I've been approached by the folks at UpLabs to consider changing the licensing scheme in dragula from MIT to GPLv3 -- essentially making dragula an open-source solution that can be used commercially by purchasing a commercial license.

    Dragula would still be open-source and free to use in open-source projects. I can't think of a lot of drawbacks here to be honest. Companies that rely on dragula can probably afford purchashing a one-time license. I could definitely use the help (money), and it would certainly motivate me to grow the open-source project so I think everybody would win.

    That being said I have my fair share of doubt in the matter, so I chose to post an issue here first and see what others think about this.

    doge 
    opened by bevacqua 18
  • Scroll on drag

    Scroll on drag

    From issue: https://github.com/bevacqua/dragula/issues/121#issuecomment-138992160

    TODO:

    • [x] vertical scroll
    • [ ] horizontal scroll
    • [ ] possibility to disable scroll
    • [ ] possibility to add the scroll triggers
    • [ ] possibility to override the scrollfunction
    • [ ] check touch
    • [ ] ~~check if we should scroll on gu-mirror position instead of mouse position?~~ (could break when containers are too close to each other)
    opened by Klaasvaak 18
  • Differentiate between drag and click events

    Differentiate between drag and click events

    delay renderMirrorImage to fire click event when mouseup quickly (defaluts 100ms).

    I npm build fail. so dist/dragula.js is old file, you need to npm build

    this is about this case #54

    opened by libo1106 17
  • Use a function as copy option value

    Use a function as copy option value

    I have a scenario when I would to decide whether the element to be dragged should be copied of not based on its status/class.

    The copy option function would return true or false based on this condition.

    For example, it could work like this:

    copy: function (el, target) { // whether element should be copied & dragged or dragged only
        return el.className === 'copy-able';
    },
    
    feature-request 
    opened by guillaumepiot 16
  • Invariant Violation when using React.js

    Invariant Violation when using React.js

    When using dragula to drag and drop react element's an error is throw because cloning elements will end up having two elements with same data-reactid attribute.

    This is what the log says:

    Uncaught Error: Invariant Violation: ReactMount: Two valid but unequal nodes with the same `data-reactid`: .0.0.0.1:$0.0.4.1.0.0.3.0
    
    opened by j0hn 16
  • Dropping also gives target element

    Dropping also gives target element

    Cool library, I would like to suggest a feature if I can.

    Dropping an element onto a target container over a target container's element should report the target container's element too.

    A scenario which this is useful is having the ability to stack elements (like cards). So a user drags to add / remove elements, but can also stack elements on top of each other. (The stacking effect not provided by dragula, but the additional API change is needed). Or getting a count, dragging element onto target element, check if elements are the same, then 'stack' (update count).

    feature-request 
    opened by hnry 15
  • Demo page and touch functionality not working on mobile Android

    Demo page and touch functionality not working on mobile Android

    Dragula seems like an excellent library, but I couldn't find anything on the documentation or previously opened issues for whether mobile Android was supported.

    When I tried out the demo page, I wasn't able to use the drag and drop functionality. I tried long-pressing, pressing, scrolling, and pinching, but none of this worked.

    Is there a flag I have to turn on, or is mobile Android not supported?

    bug 
    opened by jasonpang 14
  • Copy mode: cannot move within source

    Copy mode: cannot move within source

    I believe this line https://github.com/bevacqua/dragula/blob/master/dragula.js#L257 prevents moving (reordering) items within the source container, when copy is true.

    I think it should be possible to still reorder items within the same container.

    feature-request 
    opened by fabien 14
  • fix(sec): upgrade uglify-js to 3.14.3

    fix(sec): upgrade uglify-js to 3.14.3

    What happened?

    There are 1 security vulnerabilities found in uglify-js 3.11.0

    What did I do?

    Upgrade uglify-js from 3.11.0 to 3.14.3 for vulnerability fix

    What did you expect to happen?

    Ideally, no insecure libs should be used.

    The specification of the pull request

    PR Specification from OSCS Signed-off-by:pen4[email protected]

    opened by pen4 0
  • Horizontal sorting is buggy in RTL and flex-direction: row-reverse containers

    Horizontal sorting is buggy in RTL and flex-direction: row-reverse containers

    Please see the video below

    https://user-images.githubusercontent.com/46978227/190202901-9b3ccc2e-bfbc-4c01-a419-8b89de2c7cef.mov

    As you can see, When I drag an element to the right, it gets dropped in the left side, and vice versa.

    opened by zeyad-ahmad-aql 0
  • Idea: Possibility to access initialSibling from outside the dragula function.

    Idea: Possibility to access initialSibling from outside the dragula function.

    Hi contributers,

    canceling the dropping from within my code doesnt work because my code is waiting for a promise to resolve or reject.

    So I added:

    item['initialSibling']=_initialSibling to the drop method. Now I can insert the element at it origin:

    const promise = new Promise ((resolve, reject) => { doTheDrop (el, target, source, sibling, workflow); }); promise.then( (data) => { //great drop is ok }, (reason) => { // Rejected! source.insertBefore ( el, el.initialSibling == undefined ? null : el.initialSibling ); });

    However, I would rather not change dragula.js. Is it possible to access this property some other way?

    opened by NoCredits 0
  • Prevent dragging to an area in dragula container?

    Prevent dragging to an area in dragula container?

    Hi All! Thanks for a great kit! And all the hard work.

    We have a lib we are using from a third party that in turn uses dragula like many do.

    Is it possible... to prevent dragging to an area in a dragula container?

    Example: We want to have label divs in our dragula container. It all works great! We prepend/put a label div in the dragula container and we are able to drag both above and below it.

    But we'd like the top label div to always stay on top, not allow items to be dragged above it. Is there any way to pin to top? Disallow any dragging above an item/top item?

    Note: Clicking these label divs above in our code hide the dragula items below them. Re-clicking them allows them to show.

    Thanks! Any workarounds/thoughts appreciated. We need to use one container. so moving the label divs outside or using multiple container divs outside, won't work for us.

    opened by WriterStat 1
  • Angular 13 - Library Warning -  depends on 'dragula'. CommonJS or AMD dependencies can cause optimization bailouts.

    Angular 13 - Library Warning - depends on 'dragula'. CommonJS or AMD dependencies can cause optimization bailouts.

    Hi team, I have a library using dragula and when we build our application, we get this warning below: Warning: ...\node_modules\ng2-dragula\fesm2015\ng2-dragula.mjs depends on 'dragula'. CommonJS or AMD dependencies can cause optimization bailouts. For more info see: https://angular.io/guide/build#configuring-commonjs-dependencies

    Currently, I'm able to add "dragula" to my angular.json as allowedCommonJsDependencies part, but is there any way to provide a version of Dragula using ECMAScript bundle?

    • [ ] Read the contributing guidelines
    • [ ] Bug reports containing repro steps are likely to be fixed faster
    • [X] Feature requests should be multi-purpose, describe use cases
    • [X] For support requests or questions, please refer to our Slack channel
    opened by dimarafonseca 0
Owner
Nicolás Bevacqua
🎉 Engineering @elastic 📚 Published @mjavascript 📔 Published @buildfirst ✍ Blog @ponyfoo ⛺ Organized @nodeconf @beerjs ⛵ Conference Speaker 🛬
Nicolás Bevacqua
Simple drag and drop with dragula

Drag and drop so simple it hurts Official Angular wrapper for dragula. Notice: v2 has been released It contains a number of breaking changes. Follow t

Valor Software 1.9k Dec 18, 2022
Multiple file upload plugin with image previews, drag and drop, progress bars. S3 and Azure support, image scaling, form support, chunking, resume, pause, and tons of other features.

Fine Uploader is no longer maintained and the project has been effectively shut down. For more info, see https://github.com/FineUploader/fine-uploader

Fine Uploader 8.2k Jan 2, 2023
Drag and drop page builder and CMS for React, Vue, Angular, and more

Drag and drop page builder and CMS for React, Vue, Angular, and more Use your code components and the stack of your choice. No more being pestered for

Builder.io 4.3k Jan 9, 2023
Digispark Overmaster : free IDE TOOL allows to create and edit Digispark Scripts by the drag and drop technique,with cool GUI and easy to use it

Digispark_Overmaster Digispark Overmaster : free IDE TOOL allows to create and edit Digispark Scripts by the drag and drop technique,with cool GUI and

Yehia Elborma 5 Nov 14, 2022
Beautiful and accessible drag and drop for lists with React

react-beautiful-dnd (rbd) Beautiful and accessible drag and drop for lists with React Play with this example if you want! Core characteristics Beautif

Atlassian 28.9k Jan 7, 2023
Drag and drop library for two-dimensional, resizable and responsive lists

GridList Drag and drop library for a two-dimensional resizable and responsive list of items Demo: http://hootsuite.github.io/grid/ The GridList librar

Hootsuite 3.6k Dec 14, 2022
FileAPI — a set of javascript tools for working with files. Multiupload, drag'n'drop and chunked file upload. Images: crop, resize and auto orientation by EXIF.

FileAPI A set of JavaScript tools for working with files. Get started Download the files from the dist directory, and then: <div> <!-- "js-fileapi-

Free and open source software developed at Mail.Ru 3.6k Jan 3, 2023
DoMe is a ToDo App. you can add, delete and reorder elements of the todo list using drag and drop. You can also toggle between dark&light mode

DO ME Todo App Live Preview : DO ME Built With : - ReactJS - TailwindCSS Make sure you have: - Git - Nodejs version 14 or higher (we recommend using

Medjahdi Islem 5 Nov 18, 2022
An interactive app that allows adding, editing and removing tasks of a to-do list. Drag-and-drop featured added. Webpack was used to bundle all the Js modules in to one main Js file.

To-do List A to-do list app This app let you to set your own to-do list. Built With HTML CSS JavaScript WebPack Jest Live Page Page Link Getting Start

Kenny Salazar 7 May 5, 2022
Drag and drop library for two-dimensional, resizable and responsive lists

DEPRECATED This project is no longer maintained, please consider using react-grid-layout instead. GridList Drag and drop library for a two-dimensional

Hootsuite 3.6k Dec 14, 2022
Reorderable drag-and-drop lists for modern browsers and touch devices. No jQuery or framework required.

Sortable Sortable is a JavaScript library for reorderable drag-and-drop lists. Demo: http://sortablejs.github.io/Sortable/ Features Supports touch dev

SortableJS 26.1k Jan 5, 2023
Drag and Drop for React

React DnD Drag and Drop for React. See the docs, tutorials and examples on the website: http://react-dnd.github.io/react-dnd/ See the changelog on the

React DnD 18.7k Jan 9, 2023
Dropzone is an easy to use drag'n'drop library. It supports image previews and shows nice progress bars.

Dropzone is a JavaScript library that turns any HTML element into a dropzone. This means that a user can drag and drop a file onto it, and Dropzone wi

Dropzone 17k Dec 30, 2022
Fancytree - JavaScript tree view / tree grid plugin with support for keyboard, inline editing, filtering, checkboxes, drag'n'drop, and lazy loading

Fancytree Fancytree (sequel of DynaTree 1.x) is a JavaScript tree view / tree grid plugin with support for keyboard, inline editing, filtering, checkb

Martin Wendt 2.6k Jan 9, 2023
A Drag-and-Drop library for all JavaScript frameworks implementing an enhanced transformation mechanism to manipulate DOM elements

JavaScript Project to Manipulate DOM Elements DFlex A Drag-and-Drop library for all JavaScript frameworks implementing an enhanced transformation mech

DFlex 1.5k Jan 8, 2023
Drag and drop Argo Workflows tool.

Visual Argo Workflows Live demo The goal of this project is to make it easier for everyone on a team to construct and run their own workflows. Workflo

Artem Golub 38 Dec 22, 2022
Allow moving/copying/and creation embeds for blocks with drag-n-drop just like Logseq or Roam

Demo Features Drag-n-drop for list items in the same pane and between different panes 3 modes: move block, copy block, embed block Automatic reference

null 92 Dec 26, 2022
Drag-and-drop editor for Docassemble interviews

GraphDoc Introduction GraphDoc is a web-application that has been developed on behalf of the Maastricht Law & Tech Lab, which is part of Maastricht Un

Maastricht Law & Tech Lab 16 Dec 28, 2022
Nested Sort is a JavaScript library which helps you to sort a nested list of items via drag and drop.

Nested Sort Nested Sort is a vanilla JavaScript library, without any dependencies, which helps you to sort a nested list of items via drag and drop. U

Hesam Bahrami 40 Dec 7, 2022