34

I have an app for which I would like to be able to drag and drop to reorder and arrange colours into groups. jQuery's sortable for grids seems rather unresponsive and a little buggy. microjs recommends kbjr's DragDrop, but that library has no concept of lists, only movable objects. Sproutcore has a nice implementation, but I can't find a demo of it working for a grid.

My UI looks like this:

groups of colours

and I'd like users to be able to drag colours around within the groups as well as drag them between groups.

nornagon
  • 15,393
  • 18
  • 71
  • 85
  • 1
    A question to ask is : Is there purpose for transient grouping? I'd imagine yes. Assuming this - you should really start @ "what are these collections" in the sense of how you associate them and how that association is meaningful to the end user. edit (sorry hit enter) you'll need to listen to drag / drop placements and likely the best(easiest?) approach is the mass assignment / unassignment of classes. These classes should be representative of the collections @ some level and you will likely need several or more to describe this behavior correctly-edit2-I'm partial to Jquery.so id start there – Brandt Solovij Apr 28 '12 at 08:17

4 Answers4

48

Try this: HTML5 Sortable. It is a jQuery plugin to create sortable lists and grids using native HTML5 drag and drop API.

somdow
  • 6,268
  • 10
  • 40
  • 58
Farhadi
  • 762
  • 6
  • 6
  • 17
    The original Html5Sortable by Ali Farhadi is not actively maintained. The fork by Alexandru Badiu is the better choice. See https://github.com/voidberg/html5sortable. – Nathan Jan 25 '14 at 01:14
36

Just a friendly update, since this question came up in the search. HTML5Sortable is no longer maintained. The recommended library is Sortable. Size: 12kb minified.

Code:

var sortable = Sortable.create($('#items'));

Hope this help the next wanderer.

ahmohamed
  • 2,920
  • 20
  • 35
11

I found out that this (Nastable) is a little bit more usefull for it has nesting capabilities.

Update Actually ended up using this plugin with more options.

Hope it helps. Cheers!

adrianthedev
  • 626
  • 1
  • 11
  • 21
1

I stumbled into this problem recently as well and implemented a fairly nice approach using proximity sorting - which is not how Sortable does it, curiously enough. Article can be found here. The basic premise is this:

const orderables = Array.from(parent.children).map((element, i) => {
      return {i, element, centroid: computeCentroid(element)};
});

and then in the drag event handler:

const byDistance = orderables.map((orderable) => {
    return {distance: distanceBetweenCursorAndPoint(evt, orderable.centroid), ...orderable};
}).sort((a, b) => a.distance - b.distance);

The first element in byDistance is the one you are reordering relative to, and there is some more code to determine direction.

Julik
  • 7,676
  • 2
  • 34
  • 48