Technical Documentation: SortableJS/Sortable
โน๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference
Overview (`README.md`)
Sortable [](https://opencollective.com/Sortable) [](https://circleci.com/gh/SortableJS/Sortable) [](https://deepscan.io/dashboard#view=project&tid=3901&pid=5666&bid=43977) [](https://www.jsdelivr.com/package/npm/sortablejs) [](https://www.npmjs.com/package/sortablejs)
Sortable is a JavaScript library for reorderable drag-and-drop lists.
Demo: http://sortablejs.github.io/Sortable/
Features
- Supports touch devices and modern browsers (including IE9)
- Can drag from one list to another or within the same list
- CSS animation when moving items
- Supports drag handles and selectable text (better than voidberg's html5sortable)
- Smart auto-scrolling
- Advanced swap detection
- Smooth animations
- Multi-drag support
- Support for CSS transforms
- Built using native HTML5 drag and drop API
- Supports
- Supports any CSS library, e.g. Bootstrap
- Simple API
- Support for plugins
- CDN
- No jQuery required (but there is support)
- Typescript definitions at
@types/sortablejs
Articles
- Dragging Multiple Items in Sortable (April 26, 2019)
- Swap Thresholds and Direction (December 2, 2018)
- Sortable v1.0 โ New capabilities (December 22, 2014)
- Sorting with the help of HTML5 Drag'n'Drop API (December 23, 2013)
Getting Started
Install with NPM:
npm install sortablejs --saveInstall with Bower:
bower install --save sortablejsImport into your project:
// Default SortableJS
import Sortable from 'sortablejs';
// Core SortableJS (without default plugins)
import Sortable from 'sortablejs/modular/sortable.core.esm.js';
// Complete SortableJS (with all plugins)
import Sortable from 'sortablejs/modular/sortable.complete.esm.js';Cherrypick plugins:
// Cherrypick extra plugins
import Sortable, { MultiDrag, Swap } from 'sortablejs';
Sortable.mount(new MultiDrag(), new Swap());
// Cherrypick default plugins
import Sortable, { AutoScroll } from 'sortablejs/modular/sortable.core.esm.js';
Sortable.mount(new AutoScroll());Usage
<ul id="items">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>var el = document.getElementById('items');
var sortable = Sortable.create(el);You can use any element for the list and its elements, not just ul/li. Here is an example with divs.
Options
/* Detailed source-code truncated for AI context efficiency. */`group` option
To drag elements from one list into another, both lists must have the same group value.
You can also define whether lists can give away, give and keep a copy (clone), and receive elements.
- name:
Stringโ group name - pull:
true|false|["foo", "bar"]|'clone'|functionโ ability to move from the list.cloneโ copy the item, rather than move. Or an array of group names which the elements may be put in. Defaults totrue. - put:
true|false|["baz", "qux"]|functionโ whether elements can be added from other lists, or an array of group names from which elements can be added. - revertClone:
booleanโ revert cloned element to initial position after moving to a another list.
Demo:
- https://jsbin.com/hijetos/edit?js,output
- https://jsbin.com/nacoyah/edit?js,output โ use of complex logic in the
pullandput - https://jsbin.com/bifuyab/edit?js,output โ use
revertClone: true
`sort` option
Allow sorting inside list.
Demo: https://jsbin.com/jayedig/edit?js,output
`delay` option
Time in milliseconds to define when the sorting should start.
Unfortunately, due to browser restrictions, delaying is not possible on IE or Edge with native drag & drop.
Demo: https://jsbin.com/zosiwah/edit?js,output
`delayOnTouchOnly` option
Whether or not the delay should be applied only if the user is using touch (eg. on a mobile device). No delay will be applied in any other case. Defaults to false.
`swapThreshold` option
Percentage of the target that the swap zone will take up, as a float between 0 and 1.
Demo: http://sortablejs.github.io/Sortable#thresholds
`invertSwap` option
Set to true to set the swap zone to the sides of the target, for the effect of sorting "in between" items.
Demo: http://sortablejs.github.io/Sortable#thresholds
`invertedSwapThreshold` option
Percentage of the target that the inverted swap zone will take up, as a float between 0 and 1. If not given, will default to swapThreshold.
`direction` option
Direction that the Sortable should sort in. Can be set to 'vertical', 'horizontal', or a function, which will be called whenever a target is dragged over. Must return 'vertical' or 'horizontal'.
Example of direction detection for vertical list that includes full column and half column elements:
Sortable.create(el, {
direction: function(evt, target, dragEl) {
if (target !== null && target.className.includes('half-column') && dragEl.className.includes('half-column')) {
return 'horizontal';
}
return 'vertical';
}
});`touchStartThreshold` option
This option is similar to fallbackTolerance option.
When the delay option is set, some phones with very sensitive touch displays like the Samsung Galaxy S8 will fire
unwanted touchmove events even when your finger is not moving, resulting in the sort not triggering.
This option sets the minimum pointer movement that must occur before the delayed sorting is cancelled.
Values between 3 to 5 are good.
`disabled` options
Disables the sortable if set to true.
Demo: https://jsbin.com/sewokud/edit?js,output
var sortable = Sortable.create(list);
document.getElementById("switcher").onclick = function () {
var state = sortable.option("disabled"); // get
sortable.option("disabled", !state); // set
};`handle` option
To make list items draggable, Sortable disables text selection by the user.
That's not always desirable. To allow text selection, define a drag handler,
which is an area of every list element that allows it to be dragged around.
Demo: https://jsbin.com/numakuh/edit?html,js,output
Sortable.create(el, {
handle: ".my-handle"
});<ul>
<li><span class="my-handle">::</span> list item text one
<li><span class="my-handle">::</span> list item text two
</ul>.my-handle {
cursor: move;
cursor: -webkit-grabbing;
}`filter` option
Sortable.create(list, {
filter: ".js-remove, .js-edit",
onFilter: function (evt) {
var item = evt.item,
ctrl = evt.target;
if (Sortable.utils.is(ctrl, ".js-remove")) { // Click on remove button
item.parentNode.removeChild(item); // remove sortable item
}
else if (Sortable.utils.is(ctrl, ".js-edit")) { // Click on edit link
// ...
}
}
})`ghostClass` option
Class name for the drop placeholder (default sortable-ghost).
Demo: https://jsbin.com/henuyiw/edit?css,js,output
.ghost {
opacity: 0.4;
}Sortable.create(list, {
ghostClass: "ghost"
});`chosenClass` option
Class name for the chosen item (default sortable-chosen).
Demo: https://jsbin.com/hoqufox/edit?css,js,output
.chosen {
color: #fff;
background-color: #c00;
}Sortable.create(list, {
delay: 500,
chosenClass: "chosen"
});`forceFallback` option
If set to true, the Fallback for non HTML5 Browser will be used, even if we are using an HTML5 Browser.
This gives us the possibility to test the behaviour for older Browsers even in newer Browser, or make the Drag 'n Drop feel more consistent between Desktop , Mobile and old Browsers.
On top of that, the Fallback always generates a copy of that DOM Element and appends the class fallbackClass defined in the options. This behaviour controls the look of this 'dragged' Element.
Demo: https://jsbin.com/sibiput/edit?html,css,js,output
`fallbackTolerance` option
Emulates the native drag threshold. Specify in pixels how far the mouse should move before it's considered as a drag.
Useful if the items are also clickable like in a list of links.
When the user clicks inside a sortable element, it's not uncommon for your hand to move a little between the time you press and the time you release.
Dragging only starts if you move the pointer past a certain tolerance, so that you don't accidentally start dragging every time you click.
3 to 5 are probably good values.
`dragoverBubble` option
If set to true, the dragover event will bubble to parent sortables. Works on both fallback and native dragover event.
By default, it is false, but Sortable will only stop bubbling the event once the element has been inserted into a parent Sortable, or can be inserted into a parent Sortable, but isn't at that specific time (due to animation, etc).
Since 1.8.0, you will probably want to leave this option as false. Before 1.8.0, it may need to be true for nested sortables to work.
`removeCloneOnHide` option
If set to false, the clone is hidden by having it's CSS display property set to none.
By default, this option is true, meaning Sortable will remove the cloned element from the DOM when it is supposed to be hidden.
`emptyInsertThreshold` option
The distance (in pixels) the mouse must be from an empty sortable while dragging for the drag element to be inserted into that sortable. Defaults to 5. Set to 0 to disable this feature.
Demo: https://jsbin.com/becavoj/edit?js,output
An alternative to this option would be to set a padding on your list when it is empty.
For example:
ul:empty {
padding-bottom: 20px;
}Warning: For :empty to work, it must have no node inside (even text one).
Demo:
https://jsbin.com/yunakeg/edit?html,css,js,output
Event object ([demo](https://jsbin.com/fogujiv/edit?js,output))
- to:
HTMLElementโ list, in which moved element - from:
HTMLElementโ previous list - item:
HTMLElementโ dragged element - clone:
HTMLElement - oldIndex:
Number|undefinedโ old index within parent - newIndex:
Number|undefinedโ new index within parent - oldDraggableIndex:
Number|undefinedโ old index within parent, only counting draggable elements - newDraggableIndex:
Number|undefinedโ new index within parent, only counting draggable elements - pullMode:
String|Boolean|undefinedโ Pull mode if dragging into another sortable ("clone",true, orfalse), otherwise undefined
`move` event object
- to:
HTMLElement - from:
HTMLElement - dragged:
HTMLElement - draggedRect:
DOMRect - related:
HTMLElementโ element on which have guided - relatedRect:
DOMRect - willInsertAfter:
Booleanโtrueif will element be inserted after target (orfalseif before)
Methods
option(name:`String`[, value:`*`]):`*`
Get or set the option.
closest(el:`HTMLElement`[, selector:`String`]):`HTMLElement|null`
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
toArray():`String[]`
Serializes the sortable's item data-id's (dataIdAttr option) into an array of string.
sort(order:`String[]`, useAnimation:`Boolean`)
Sorts the elements according to the array.
var order = sortable.toArray();
sortable.sort(order.reverse(), true); // applysave()
Save the current sorting (see store)
destroy()
Removes the sortable functionality completely.
Store
Saving and restoring of the sort.
<ul>
<li data-id="1">order</li>
<li data-id="2">save</li>
<li data-id="3">restore</li>
</ul>Sortable.create(el, {
group: "localStorage-example",
store: {
/**
* Get the order of elements. Called once during initialization.
* @param {Sortable} sortable
* @returns {Array}
*/
get: function (sortable) {
var order = localStorage.getItem(sortable.options.group.name);
return order ? order.split('|') : [];
},
/**
* Save the order of elements. Called onEnd (when the item is dropped).
* @param {Sortable} sortable
*/
set: function (sortable) {
var order = sortable.toArray();
localStorage.setItem(sortable.options.group.name, order.join('|'));
}
}
})Bootstrap
Demo: https://jsbin.com/visimub/edit?html,js,output
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"/>
<script src="http://SortableJS.github.io/Sortable/Sortable.js"></script>
<ul id="simpleList" class="list-group">
<li class="list-group-item">This is <a href="http://SortableJS.github.io/Sortable/">Sortable</a></li>
<li class="list-group-item">It works with Bootstrap...</li>
<li class="list-group-item">...out of the box.</li>
<li class="list-group-item">It has support for touch devices.</li>
<li class="list-group-item">Just drag some elements around.</li>
</ul>
<script>
// Simple list
Sortable.create(simpleList, { /* options */ });
</script>Static methods & properties
Sortable.create(el:`HTMLElement`[, options:`Object`]):`Sortable`
Create new instance.
Sortable.active:`Sortable`
The active Sortable instance.
Sortable.dragged:`HTMLElement`
The element being dragged.
Sortable.ghost:`HTMLElement`
The ghost element.
Sortable.clone:`HTMLElement`
The clone element.
Sortable.get(element:`HTMLElement`):`Sortable`
Get the Sortable instance on an element.
Sortable.mount(plugin:`...SortablePlugin|SortablePlugin[]`)
Mounts a plugin to Sortable.
Sortable.utils
- on(el
:HTMLElement, event:String, fn:Function) โ attach an event handler function - off(el
:HTMLElement, event:String, fn:Function) โ remove an event handler - css(el
:HTMLElement):Objectโ get the values of all the CSS properties - css(el
:HTMLElement, prop:String):Mixedโ get the value of style properties - css(el
:HTMLElement, prop:String, value:String) โ set one CSS properties - css(el
:HTMLElement, props:Object) โ set more CSS properties - find(ctx
:HTMLElement, tagName:String[, iterator:Function]):Arrayโ get elements by tag name - bind(ctx
:Mixed, fn:Function):Functionโ Takes a function and returns a new one that will always have a particular context - is(el
:HTMLElement, selector:String):Booleanโ check the current matched set of elements against a selector - closest(el
:HTMLElement, selector:String[, ctx:HTMLElement]):HTMLElement|Nullโ for each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree - clone(el
:HTMLElement):HTMLElementโ create a deep copy of the set of matched elements - toggleClass(el
:HTMLElement, name:String, state:Boolean) โ add or remove one classes from each element - detectDirection(el
:HTMLElement):Stringโ automatically detect the direction of the element as either'vertical'or'horizontal' - index(el
:HTMLElement, selector:String):Numberโ index of the element within its parent for a selected set of elements - getChild(el
:HTMLElement, childNum:Number, options:Object, includeDragEl:Boolean):HTMLElementโ get the draggable element at a given index of draggable elements within a Sortable instance - expando
:Stringโ expando property name for internal use, sortableListElement[expando] returns the Sortable instance of that elemenet
Plugins
Extra Plugins (included in complete versions)
Default Plugins (included in default versions)
CDN
<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>Contributing (Issue/PR)
Please, read this.
Contributors
Code Contributors
This project exists thanks to all the people who contribute. [Contribute].
Financial Contributors
Become a financial contributor and help us sustain our community. [Contribute]
Individuals
Organizations
Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]
MIT LICENSE
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Overview (`plugins/README.md`)
Creating Sortable Plugins
Sortable plugins are plugins that can be directly mounted to the Sortable class. They are a powerful way of modifying the default behaviour of Sortable beyond what simply using events alone allows. To mount your plugin to Sortable, it must pass a constructor function to the Sortable.mount function. This constructor function will be called (with the new keyword in front of it) whenever a Sortable instance with your plugin enabled is initialized. The constructor function will be called with the parameters sortable and el, which is the HTMLElement that the Sortable is being initialized on. This means that there will be a new instance of your plugin each time it is enabled in a Sortable.
Constructor Parameters
sortable: Sortable โ The sortable that the plugin is being initialized on
el: HTMLElement โ The element that the sortable is being initialized on
options: Object โ The options object that the user has passed into Sortable (not merged with defaults yet)
Static Properties
The constructor function passed to Sortable.mount may contain several static properties and methods. The following static properties may be defined:
pluginName: String (Required)
The name of the option that the user will use in their sortable's options to enable the plugin. Should start with a lower case and be camel-cased. For example: 'multiDrag'. This is also the property name that the plugin's instance will be under in a sortable instance (ex. sortableInstance.multiDrag).
utils: Object
Object containing functions that will be added to the Sortable.utils static object on the Sortable class.
eventOptions(eventName: String): Function
A function that is called whenever Sortable fires an event. This function should return an object to be combined with the event object that Sortable will emit. The function will be called in the context of the instance of the plugin on the Sortable that is firing the event (ie. the this keyword will be the plugin instance).
initializeByDefault: Boolean
Determines whether or not the plugin will always be initialized on every new Sortable instance. If this option is enabled, it does not mean that by default the plugin will be enabled on the Sortable - this must still be done in the options via the plugin's pluginName, or it can be enabled by default if your plugin specifies it's pluginName as a default option that is truthy. Since the plugin will already be initialized on every Sortable instance, it can also be enabled dynamically via sortableInstance.option('pluginName', true).
It is a good idea to have this option set to false if the plugin modifies the behaviour of Sortable in such a way that enabling or disabling the plugin dynamically could cause it to break. Likewise, this option should be disabled if the plugin should only be instantiated on Sortables in which that plugin is enabled.
This option defaults to true.
optionListeners: Object
An object that may contain event listeners that are fired when a specific option is updated.
These listeners are useful because the user's provided options are not necessarily unchanging once the plugin is initialized, and could be changed dynamically via the option() method.
The listener will be fired in the context of the instance of the plugin that it is being changed in (ie. the this keyword will be the instance of your plugin).
The name of the method should match the name of the option it listens for. The new value of the option will be passed in as an argument, and any returned value will be what the option is stored as. If no value is returned, the option will be stored as the value the user provided.
Example:
Plugin.name = 'generateTitle';
Plugin.optionListeners = {
// Listen for option 'generateTitle'
generateTitle: function(title) {
// Store the option in all caps
return title.toUpperCase();
// OR save it to this instance of your plugin as a private field.
// This way it can be accessed in events, but will not modify the user's options.
this.titleAllCaps = title.toUpperCase();
}
};Plugin Options
Plugins may have custom default options or may override the defaults of other options. In order to do this, there must be a defaults object on the initialized plugin. This can be set in the plugin's prototype, or during the initialization of the plugin (when the el is available). For example:
function myPlugin(sortable, el, options) {
this.defaults = {
color: el.style.backgroundColor
};
}
Sortable.mount(myPlugin);Plugin Events
Context
The events will be fired in the context of their own parent object (ie. context is not changed), however the plugin instance's Sortable instance is available under this.sortable. Likewise, the options are available under this.options.
Event List
The following table contains details on the events that a plugin may handle in the prototype of the plugin's constructor function.
| Event Name | Description | Cancelable? | Cancel Behaviour | Event Type | Custom Event Object Properties |
|---|---|---|---|---|---|
| filter | Fired when the element is filtered, and dragging is therefore canceled | No | - | Normal | None |
| delayStart | Fired when the delay starts, even if there is no delay | Yes | Cancels sorting | Normal | None |
| delayEnded | Fired when the delay ends, even if there is no delay | Yes | Cancels sorting | Normal | None |
| setupClone | Fired when Sortable clones the dragged element | Yes | Cancels normal clone setup | Normal | None |
| dragStart | Fired when the dragging is first started | Yes | Cancels sorting | Normal | None |
| clone | Fired when the clone is inserted into the DOM (if removeCloneOnHide: false). Tick after dragStart. |
Yes | Cancels normal clone insertion & hiding | Normal | None |
| dragStarted | Fired tick after dragStart | No | - | Normal | None |
| dragOver | Fired when the user drags over a sortable | Yes | Cancels normal dragover behaviour | DragOver | None |
| dragOverValid | Fired when the user drags over a sortable that the dragged item can be inserted into | Yes | Cancels normal valid dragover behaviour | DragOver | None |
| revert | Fired when the dragged item is reverted to it's original position when entering it's sort:false root |
Yes | Cancels normal reverting, but is still completed() | DragOver | None |
| dragOverCompleted | Fired when dragOver is completed (ie. bubbling is disabled). To check if inserted, use inserted even property. |
No | - | DragOver | insertion: Boolean โ Whether or not the dragged element was inserted |
| dragOverAnimationCapture | Fired right before the animation state is captured in dragOver | No | - | DragOver | None |
| dragOverAnimationComplete | Fired after the animation is completed after a dragOver insertion | No | - | DragOver | None |
| drop | Fired on drop | Yes | Cancels normal drop behavior | Normal | None |
| nulling | Fired when the plugin should preform cleanups, once all drop events have fired | No | - | Normal | None |
| destroy | Fired when Sortable is destroyed | No | - | Normal | None |
Global Events
Normally, an event will only be fired in a plugin if the plugin is enabled on the Sortable from which the event is being fired. However, it sometimes may be desirable for a plugin to listen in on an event from Sortables in which it is not enabled on. This is possible with global events. For an event to be global, simply add the suffix 'Global' to the event's name (casing matters) (eg. dragStartGlobal).
Please note that your plugin must be initialized on any Sortable from which it expects to recieve events, and that includes global events. In other words, you will want to keep the initializeByDefault option as it's default true value if your plugin needs to recieve events from Sortables it is not enabled on.
Please also note that if both normal and global event handlers are set, the global event handler will always be fired before the regular one.
Event Object
An object with the following properties is passed as an argument to each plugin event when it is fired.
Properties:
dragEl: HTMLElement โ The element being dragged
parentEl: HTMLElement โ The element that the dragged element is currently in
ghostEl: HTMLElement|undefined โ If using fallback, the element dragged under the cursor (undefined until after dragStarted plugin event)
rootEl: HTMLElement โ The element that the dragged element originated from
nextEl: HTMLElement โ The original next sibling of dragEl
cloneEl: HTMLElement|undefined โ The clone element (undefined until after setupClone plugin event)
cloneHidden: Boolean โ Whether or not the clone is hidden
dragStarted: Boolean โ Boolean indicating whether or not the dragStart event has fired
putSortable: Sortable|undefined โ The element that dragEl is dragged into from it's root, otherwise undefined
activeSortable: Sortable โ The active Sortable instance
originalEvent: Event โ The original HTML event corresponding to the Sortable event
oldIndex: Number โ The old index of dragEl
oldDraggableIndex: Number โ The old index of dragEl, only counting draggable elements
newIndex: Number โ The new index of dragEl
newDraggableIndex: Number โ The new index of dragEl, only counting draggable elements
Methods:
cloneNowHidden() โ Function to be called if the plugin has hidden the clone
cloneNowShown() โ Function to be called if the plugin has shown the clone
hideGhostForTarget() โ Hides the fallback ghost element if CSS pointer-events are not available. Call this before using document.elementFromPoint at the mouse position.
unhideGhostForTarget() โ Unhides the ghost element. To be called after hideGhostForTarget().
dispatchSortableEvent(eventName: String) โ Function that can be used to emit an event on the current sortable while sorting, with all usual event properties set (eg. indexes, rootEl, cloneEl, originalEvent, etc.).
DragOverEvent Object
This event is passed to dragover events, and extends the normal event object.
Properties:
isOwner: Boolean โ Whether or not the dragged over sortable currently contains the dragged element
axis: String โ Direction of the dragged over sortable, 'vertical' or 'horizontal'
revert: Boolean โ Whether or not the dragged element is being reverted to it's original position from another position
dragRect: DOMRect โ DOMRect of the dragged element
targetRect: DOMRect โ DOMRect of the target element
canSort: Boolean โ Whether or not sorting is enabled in the dragged over sortable
fromSortable: Sortable โ The sortable that the dragged element is coming from
target: HTMLElement โ The sortable item that is being dragged over
Methods:
onMove(target: HTMLElement, after: Boolean): Boolean|Number โ Calls the onMove function the user specified in the options
changed() โ Fires the onChange event with event properties preconfigured
completed(insertion: Boolean) โ Should be called when dragover has "completed", meaning bubbling should be stopped. If insertion is true, Sortable will treat it as if the dragged element was inserted into the sortable, and hide/show clone, set ghost class, animate, etc.
Overview (`plugins/AutoScroll/README.md`)
AutoScroll
This plugin allows for the page to automatically scroll during dragging near a scrollable element's edge on mobile devices and IE9 (or whenever fallback is enabled), and also enhances most browser's native drag-and-drop autoscrolling.
Demo:
window: https://jsbin.com/dosilir/edit?js,outputoverflow: hidden: https://jsbin.com/xecihez/edit?html,js,output
This plugin is a default plugin, and is included in the default UMD and ESM builds of Sortable
Mounting
import { Sortable, AutoScroll } from 'sortablejs';
Sortable.mount(new AutoScroll());Options
new Sortable(el, {
scroll: true, // Enable the plugin. Can be HTMLElement.
forceAutoScrollFallback: false, // force autoscroll plugin to enable even when native browser autoscroll is available
scrollFn: function(offsetX, offsetY, originalEvent, touchEvt, hoverTargetEl) { ... }, // if you have custom scrollbar scrollFn may be used for autoscrolling
scrollSensitivity: 30, // px, how near the mouse must be to an edge to start scrolling.
scrollSpeed: 10, // px, speed of the scrolling
bubbleScroll: true // apply autoscroll to all parent elements, allowing for easier movement
});`scroll` option
Enables the plugin. Defaults to true. May also be set to an HTMLElement which will be where autoscrolling is rooted.
Note: Just because this plugin is enabled does not mean that it will always be used for autoscrolling. Some browsers have native drag and drop autoscroll, in which case this autoscroll plugin won't be invoked. If you wish to have this always be invoked for autoscrolling, set the option forceAutoScrollFallback to true.
Demo:
window: https://jsbin.com/dosilir/edit?js,outputoverflow: hidden: https://jsbin.com/xecihez/edit?html,js,output
`forceAutoScrollFallback` option
Enables sortable's autoscroll even when the browser can handle it (with native drag and drop). Defaults to false. This will not disable the native autoscrolling. Note that setting forceFallback: true in the sortable options will also enable this.
`scrollFn` option
Useful when you have custom scrollbar with dedicated scroll function.
Defines a function that will be used for autoscrolling. Sortable uses el.scrollTop/el.scrollLeft by default. Set this option if you wish to handle it differently.
This function should return 'continue' if it wishes to allow Sortable's native autoscrolling, otherwise Sortable will not scroll anything if this option is set.
Note that this option will only work if Sortable's autoscroll function is invoked.
It is invoked if any of the following are true:
- The
forceFallback: trueoption is set - It is a mobile device
- The browser is either Safari, Internet Explorer, or Edge
`scrollSensitivity` option
Defines how near the mouse must be to an edge to start scrolling.
Note that this option will only work if Sortable's autoscroll function is invoked.
It is invoked if any of the following are true:
- The
forceFallback: trueoption is set - It is a mobile device
- The browser is either Safari, Internet Explorer, or Edge
`scrollSpeed` option
The speed at which the window should scroll once the mouse pointer gets within the scrollSensitivity distance.
Note that this option will only work if Sortable's autoscroll function is invoked.
It is invoked if any of the following are true:
- The
forceFallback: trueoption is set - It is a mobile device
- The browser is either Safari, Internet Explorer, or Edge
`bubbleScroll` option
If set to true, the normal autoscroll function will also be applied to all parent elements of the element the user is dragging over.
Demo: https://jsbin.com/kesewor/edit?html,js,output
Overview (`plugins/MultiDrag/README.md`)
MultiDrag Plugin
This plugin allows users to select multiple items within a sortable at once, and drag them as one item.
Once placed, the items will unfold into their original order, but all beside each other at the new position.
Read More
Demo: https://jsbin.com/wopavom/edit?js,output
Mounting
import { Sortable, MultiDrag } from 'sortablejs';
Sortable.mount(new MultiDrag());Options
new Sortable(el, {
multiDrag: true, // Enable the plugin
selectedClass: "sortable-selected", // Class name for selected item
multiDragKey: null, // Key that must be down for items to be selected
avoidImplicitDeselect: false, // true - if you don't want to deselect items on outside click
// Called when an item is selected
onSelect: function(/**Event*/evt) {
evt.item // The selected item
},
// Called when an item is deselected
onDeselect: function(/**Event*/evt) {
evt.item // The deselected item
}
});`multiDragKey` option
The key that must be down for multiple items to be selected. The default is null, meaning no key must be down.
For special keys, such as the CTRL key, simply specify the option as 'CTRL' (casing does not matter).
`selectedClass` option
Class name for the selected item(s) if multiDrag is enabled. Defaults to sortable-selected.
.selected {
background-color: #f9c7c8;
border: solid red 1px;
}Sortable.create(list, {
multiDrag: true,
selectedClass: "selected"
});Event Properties
- items:
HTMLElement[]โ Array of selected items, or empty - clones:
HTMLElement[]โ Array of clones, or empty - oldIndicies:
Index[]โ Array containing information on the old indicies of the selected elements. - newIndicies:
Index[]โ Array containing information on the new indicies of the selected elements.
Index Object
- element:
HTMLElementโ The element whose index is being given - index:
Numberโ The index of the element
Note on `newIndicies`
For any event that is fired during sorting, the index of any selected element that is not the main dragged element is given as -1.
This is because it has either been removed from the DOM, or because it is in a folding animation (folding to the dragged element) and will be removed after this animation is complete.
Sortable.utils
- select(el:
HTMLElement) โ select the given multi-drag item - deselect(el:
HTMLElement) โ deselect the given multi-drag item
Overview (`plugins/OnSpill/README.md`)
OnSpill Plugins
This file contains two seperate plugins, RemoveOnSpill and RevertOnSpill. They can be imported individually, or the default export (an array of both plugins) can be passed to Sortable.mount as well.
These plugins are default plugins, and are included in the default UMD and ESM builds of Sortable
Mounting
import { Sortable, OnSpill } from 'sortablejs/modular/sortable.core.esm';
Sortable.mount(OnSpill);RevertOnSpill Plugin
This plugin, when enabled, will cause the dragged item to be reverted to it's original position if it is spilled (ie. it is dropped outside of a valid Sortable drop target)
Options
new Sortable(el, {
revertOnSpill: true, // Enable plugin
// Called when item is spilled
onSpill: function(/**Event*/evt) {
evt.item // The spilled item
}
});RemoveOnSpill Plugin
This plugin, when enabled, will cause the dragged item to be removed from the DOM if it is spilled (ie. it is dropped outside of a valid Sortable drop target)
Options
new Sortable(el, {
removeOnSpill: true, // Enable plugin
// Called when item is spilled
onSpill: function(/**Event*/evt) {
evt.item // The spilled item
}
});Overview (`plugins/Swap/README.md`)
Swap Plugin
This plugin modifies the behaviour of Sortable to allow for items to be swapped with eachother rather than sorted. Once dragging starts, the user can drag over other items and there will be no change in the elements. However, the item that the user drops on will be swapped with the originally dragged item.
Demo: https://jsbin.com/yejehog/edit?html,js,output
Mounting
import { Sortable, Swap } from 'sortablejs/modular/sortable.core.esm';
Sortable.mount(new Swap());Options
new Sortable(el, {
swap: true, // Enable swap mode
swapClass: "sortable-swap-highlight" // Class name for swap item (if swap mode is enabled)
});`swapClass` option
Class name for the item to be swapped with, if swap mode is enabled. Defaults to sortable-swap-highlight.
.highlighted {
background-color: #9AB6F1;
}Sortable.create(list, {
swap: true,
swapClass: "highlighted"
});Event Properties
- swapItem:
HTMLElement|undefinedโ The element that the dragged element was swapped with
--- METRICS ---
- Files Extracted: 6
- Estimated Token Budget: ~11259 tokens
- Canonical Reference: https://codewiki.google/github.com/SortableJS/Sortable