### Installation and Import Patterns
Source: https://context7.com/sortablejs/sortable/llms.txt
Provides instructions for installing SortableJS via npm and importing different builds (default, core, complete) or cherry-picking plugins. Also includes CDN and Bower usage.
```APIDOC
## Installation and Import Patterns
SortableJS supports UMD, ESM, and CDN usage with full, default, and core bundles available to control which plugins are included.
```bash
npm install sortablejs
```
```js
// Default build (includes AutoScroll + OnSpill plugins)
import Sortable from 'sortablejs';
// Core build (no default plugins — smallest bundle)
import Sortable from 'sortablejs/modular/sortable.core.esm.js';
// Complete build (all plugins pre-mounted)
import Sortable from 'sortablejs/modular/sortable.complete.esm.js';
// Cherrypick extra plugins from default build
import Sortable, { MultiDrag, Swap } from 'sortablejs';
Sortable.mount(new MultiDrag(), new Swap());
// Cherrypick default plugins from core build
import Sortable, { AutoScroll } from 'sortablejs/modular/sortable.core.esm.js';
Sortable.mount(new AutoScroll());
```
```html
```
```js
// Bower
// bower install --save sortablejs
```
```
--------------------------------
### SortableJS Installation via NPM
Source: https://context7.com/sortablejs/sortable/llms.txt
Install SortableJS using npm for use in your project. This command installs the latest version of the library.
```bash
npm install sortablejs
```
--------------------------------
### Sortable.mount(...plugins)
Source: https://context7.com/sortablejs/sortable/llms.txt
Installs one or more plugin constructors onto the Sortable class. This must be called before creating any Sortable instances that utilize these plugins.
```APIDOC
## Sortable.mount(...plugins)
### Description
Static method to install one or more plugin constructors onto the Sortable class. Must be called before creating any Sortable instances that use those plugins. Plugins also contribute to `Sortable.utils`.
### Parameters
#### Path Parameters
- **plugins** (...PluginConstructor) - Required - One or more plugin constructors to mount.
### Request Example
```javascript
import Sortable, { MultiDrag, Swap } from 'sortablejs';
// Mount all needed plugins once, before any Sortable.create calls
Sortable.mount(new MultiDrag(), new Swap());
// Or mount from array
Sortable.mount([new MultiDrag(), new Swap()]);
```
### Response
This method does not return a value.
```
--------------------------------
### Register Plugins with `Sortable.mount()`
Source: https://context7.com/sortablejs/sortable/llms.txt
Install plugin constructors using `Sortable.mount(...plugins)` before creating Sortable instances that utilize them. Plugins extend Sortable's functionality and are also available via `Sortable.utils`.
```javascript
import Sortable, { MultiDrag, Swap } from 'sortablejs';
// Mount all needed plugins once, before any Sortable.create calls
Sortable.mount(new MultiDrag(), new Swap());
// Or mount from array
Sortable.mount([new MultiDrag(), new Swap()]);
// Now create instances using plugin options
const sortable = Sortable.create(document.getElementById('list'), {
multiDrag: true,
selectedClass: 'selected',
swap: true,
swapClass: 'highlight',
animation: 150
});
```
--------------------------------
### Define Plugin Name and Option Listeners
Source: https://github.com/sortablejs/sortable/blob/master/plugins/README.md
Example of setting a plugin's name and defining listeners for option changes. The listener can modify the option value or store it privately.
```javascript
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();
}
};
```
--------------------------------
### SortableJS Installation via CDN
Source: https://context7.com/sortablejs/sortable/llms.txt
Include SortableJS in your HTML using a CDN link for the latest minified UMD build. Initialize Sortable after the script is loaded.
```html
```
--------------------------------
### Bootstrap Integration with SortableJS
Source: https://github.com/sortablejs/sortable/blob/master/README.md
Demonstrates how to use SortableJS with Bootstrap elements. This example includes the necessary Bootstrap CSS and SortableJS library, then initializes Sortable on a Bootstrap list.
```html
```
--------------------------------
### SortableJS Installation via Bower
Source: https://context7.com/sortablejs/sortable/llms.txt
Install SortableJS using Bower package manager. This command adds SortableJS to your project's dependencies.
```bash
// Bower
// bower install --save sortablejs
```
--------------------------------
### Save and retrieve sort order using localStorage
Source: https://github.com/sortablejs/sortable/wiki/Sortable-v1.0-—-New-capabilities
Configure the `store` property with `get` and `set` functions to persist the sorting order using localStorage. The `get` function retrieves the order on initialization, and the `set` function saves it whenever the sorting is modified. Ensure the `group` option is set for this to work correctly.
```javascript
Sortable.create(users, {
store: {
// Sorting acquisition (called during initialization)
get: function (sortable) {
var order = localStorage.getItem(sortable.options.group);
return order ? order.split('|') : [];
},
// Saving the acquired sorting (called each time upon sorting modification)
set: function (sortable) {
var order = sortable.toArray();
localStorage.setItem(sortable.options.group, order.join('|'));
}
}
});
```
--------------------------------
### CDN Link for SortableJS
Source: https://github.com/sortablejs/sortable/blob/master/README.md
Provides a CDN link to include the latest version of SortableJS in your project. This is a quick way to add the library without local installation.
```html
```
--------------------------------
### Get or Set Sortable Options at Runtime
Source: https://context7.com/sortablejs/sortable/llms.txt
The `option()` method allows reading or updating configuration options on a live Sortable instance. Setting the `group` option triggers internal group preparation and invokes plugin listeners. Use this to dynamically change behavior like disabling/enabling.
```javascript
const sortable = Sortable.create(document.getElementById('list'), {
disabled: false,
animation: 150
});
// Get current option value
console.log(sortable.option('disabled')); // false
// Dynamically disable/re-enable
document.getElementById('toggle').addEventListener('click', () => {
const current = sortable.option('disabled');
sortable.option('disabled', !current);
console.log('Sortable is now', !current ? 'disabled' : 'enabled');
});
// Update group dynamically
sortable.option('group', { name: 'new-group', pull: true, put: false });
```
--------------------------------
### sortable.option(name[, value])
Source: https://context7.com/sortablejs/sortable/llms.txt
Allows getting or setting configuration options on a live Sortable instance at runtime. Updating options like 'group' can trigger internal reconfigurations.
```APIDOC
## sortable.option(name[, value]) — Get or set an option at runtime
Reads or updates a configuration option on a live Sortable instance. Setting `group` triggers internal group preparation. Plugin option listeners are also invoked.
```js
const sortable = Sortable.create(document.getElementById('list'), {
disabled: false,
animation: 150
});
// Get current option value
console.log(sortable.option('disabled')); // false
// Dynamically disable/re-enable
document.getElementById('toggle').addEventListener('click', () => {
const current = sortable.option('disabled');
sortable.option('disabled', !current);
console.log('Sortable is now', !current ? 'disabled' : 'enabled');
});
// Update group dynamically
sortable.option('group', { name: 'new-group', pull: true, put: false });
```
```
--------------------------------
### Set Touch Start Threshold with SortableJS
Source: https://github.com/sortablejs/sortable/blob/master/README.md
The `touchStartThreshold` option defines the minimum pointer movement required to cancel delayed sorting, preventing unwanted cancels on sensitive touch screens. Values between 3 and 5 are recommended.
```javascript
Sortable.create(el, {
touchStartThreshold: 5
});
```
--------------------------------
### SortableJS Initialization with Options
Source: https://github.com/sortablejs/sortable/blob/master/README.md
Demonstrates how to initialize a SortableJS instance with a comprehensive set of configuration options.
```APIDOC
## SortableJS Initialization
### Description
Initializes a new SortableJS instance on a given HTML element with various configuration options to control its behavior, appearance, and event handling.
### Method
```javascript
new Sortable(el, options)
```
### Parameters
#### `el`
- **el** (HTMLElement) - The HTML element to make sortable.
#### `options`
- **group** (string | object) - Group configuration for sorting between lists. Can be a string name or an object with `name`, `pull`, and `put` properties.
- **sort** (boolean) - Enables or disables sorting within the list. Defaults to `true`.
- **delay** (number) - Time in milliseconds to define when the sorting should start. Defaults to `0`.
- **delayOnTouchOnly** (boolean) - If `true`, delay only applies on touch devices. Defaults to `false`.
- **touchStartThreshold** (number) - Pixels the mouse should move before cancelling a delayed drag event. Defaults to `0`.
- **disabled** (boolean) - Disables the sortable if set to `true`. Defaults to `false`.
- **store** (object | null) - Configuration for storing and retrieving sortable state. See Store documentation.
- **animation** (number) - Speed in ms for animations when moving items. `0` means no animation. Defaults to `150`.
- **easing** (string) - Easing function for animations. Defaults to `"cubic-bezier(1, 0, 0, 1)"`.
- **handle** (string) - CSS selector for drag handles within list items.
- **filter** (string | Function) - Selectors or a function that determines which elements do not lead to dragging.
- **preventOnFilter** (boolean) - If `true`, calls `event.preventDefault()` when `filter` is triggered. Defaults to `true`.
- **draggable** (string) - CSS selector specifying which items inside the element should be draggable. Defaults to `.item`.
- **dataIdAttr** (string) - HTML attribute used by the `toArray()` method to get item IDs. Defaults to `"data-id"`.
- **ghostClass** (string) - Class name for the drop placeholder element. Defaults to `"sortable-ghost"`.
- **chosenClass** (string) - Class name for the chosen item element. Defaults to `"sortable-chosen"`.
- **dragClass** (string) - Class name for the dragging item element. Defaults to `"sortable-drag"`.
- **swapThreshold** (number) - Threshold of the swap zone. Defaults to `1`.
- **invertSwap** (boolean) - If `true`, always uses inverted swap zone. Defaults to `false`.
- **invertedSwapThreshold** (number) - Threshold of the inverted swap zone. Defaults to `swapThreshold` value.
- **direction** (string) - Direction of Sortable (`"horizontal"` or `"vertical"`). Auto-detected if not given.
- **forceFallback** (boolean) - Ignores HTML5 DnD behavior and forces fallback. Defaults to `false`.
- **fallbackClass** (string) - Class name for the cloned DOM Element when using `forceFallback`. Defaults to `"sortable-fallback"`.
- **fallbackOnBody** (boolean) - Appends the cloned DOM Element to the document's body. Defaults to `false`.
- **fallbackTolerance** (number) - Pixels the mouse should move before it's considered a drag when using fallback. Defaults to `0`.
- **dragoverBubble** (boolean) - Controls event bubbling for `dragover`. Defaults to `false`.
- **removeCloneOnHide** (boolean) - Removes the clone element when it's not showing. Defaults to `true`.
- **emptyInsertThreshold** (number) - Distance in pixels from an empty sortable to insert a dragged element. Defaults to `5`.
- **setData** (Function) - Callback function to set data on the `DataTransfer` object. Receives `dataTransfer` and `dragEl`.
- **onChoose** (Function) - Callback when an element is chosen. Receives `Event` object with `oldIndex`.
- **onUnchoose** (Function) - Callback when an element is unchosen. Receives `Event` object with properties similar to `onEnd`.
- **onStart** (Function) - Callback when dragging starts. Receives `Event` object with `oldIndex`.
- **onEnd** (Function) - Callback when dragging ends. Receives `Event` object with properties like `item`, `to`, `from`, `oldIndex`, `newIndex`, `clone`, `pullMode`.
- **onAdd** (Function) - Callback when an element is added to the list from another list. Receives `Event` object with properties similar to `onEnd`.
- **onUpdate** (Function) - Callback when sorting within the list changes. Receives `Event` object with properties similar to `onEnd`.
- **onSort** (Function) - Callback for any change to the list (add, update, remove). Receives `Event` object with properties similar to `onEnd`.
- **onRemove** (Function) - Callback when an element is removed from the list into another list. Receives `Event` object with properties similar to `onEnd`.
- **onFilter** (Function) - Callback when an attempt is made to drag a filtered element. Receives `Event` object with `item`.
- **onMove** (Function) - Callback when an item is moved in the list or between lists. Receives `Event` object and `originalEvent`. Can return values to control insertion behavior.
- **onClone** (Function) - Callback when a clone of an element is created. Receives `Event` object with `item` and `clone`.
### Request Example
```javascript
var sortable = new Sortable(document.getElementById('my-list'), {
group: 'shared',
animation: 150,
onEnd: function (evt) {
console.log('Item moved from ' + evt.oldIndex + ' to ' + evt.newIndex);
}
});
```
### Response
N/A (This is a constructor, not an endpoint)
```
--------------------------------
### Retrieve Sortable Instance with `Sortable.get()`
Source: https://context7.com/sortablejs/sortable/llms.txt
Use `Sortable.get(element)` to retrieve the Sortable instance associated with a DOM element. This is useful for interacting with an existing Sortable list, for example, to get its current order or check its disabled state.
```javascript
Sortable.create(document.getElementById('list-a'), { group: 'shared', animation: 150 });
Sortable.create(document.getElementById('list-b'), { group: 'shared', animation: 150 });
document.addEventListener('click', (evt) => {
const list = evt.target.closest('ul');
if (list) {
const instance = Sortable.get(list);
if (instance) {
console.log('Current order:', instance.toArray());
console.log('Is disabled:', instance.option('disabled'));
}
}
});
```
--------------------------------
### Cherrypick and Mount Default Plugins
Source: https://github.com/sortablejs/sortable/blob/master/README.md
Import specific default plugins like AutoScroll from the modular core, then mount them.
```javascript
import Sortable, { AutoScroll } from 'sortablejs/modular/sortable.core.esm.js';
Sortable.mount(new AutoScroll());
```
--------------------------------
### Cherrypick and Mount Extra Plugins
Source: https://github.com/sortablejs/sortable/blob/master/README.md
Import specific extra plugins like MultiDrag and Swap, then mount them with SortableJS.
```javascript
import Sortable, { MultiDrag, Swap } from 'sortablejs';
Sortable.mount(new MultiDrag(), new Swap());
```
--------------------------------
### Set Custom Default Options for a Plugin
Source: https://github.com/sortablejs/sortable/blob/master/plugins/README.md
Demonstrates how a plugin can define its own default options, which can be set during initialization using the provided element's style.
```javascript
function myPlugin(sortable, el, options) {
this.defaults = {
color: el.style.backgroundColor
};
}
Sortable.mount(myPlugin);
```
--------------------------------
### Custom Swap Highlight Class
Source: https://github.com/sortablejs/sortable/blob/master/plugins/Swap/README.md
Define custom CSS for the swap highlight class to visually indicate the item that will be swapped. This example uses a simple background color.
```css
.highlighted {
background-color: #9AB6F1;
}
```
--------------------------------
### Mount SortableJS Swap Plugin
Source: https://github.com/sortablejs/sortable/blob/master/plugins/Swap/README.md
Mount the Swap plugin to enable its functionality. Ensure you import Sortable and Swap from the modular entry point.
```javascript
import { Sortable, Swap } from 'sortablejs/modular/sortable.core.esm';
Sortable.mount(new Swap());
```
--------------------------------
### Initialize SortableJS in Parent and IFrame
Source: https://github.com/sortablejs/sortable/blob/master/st/iframe/index.html
Initializes SortableJS on a list in the parent document and then creates an iframe, initializing SortableJS on a list within the iframe once it loads. Both lists share the 'shared' group for drag-and-drop.
```javascript
(function () { Sortable.create(simpleList, {group: 'shared'}); var iframe = document.createElement('iframe'); iframe.src = 'frame.html'; iframe.width = '100%'; iframe.onload = function () { var doc = iframe.contentDocument, list = doc.getElementById('listWithHandle'); Sortable.create(list, {group: 'shared'}); }; document.body.appendChild(iframe); })();
```
--------------------------------
### SortableJS onChange Event
Source: https://github.com/sortablejs/sortable/blob/master/README.md
Use the onChange event to detect when a dragged element changes its position. The evt.newIndex property is often used to get the current index of the dragged element. This event shares properties with the onEnd event.
```javascript
onChange: function(/**Event*/evt) {
evt.newIndex // most likely why this event is used is to get the dragging element's current index
// same properties as onEnd
}
});
```
```
--------------------------------
### Initialize Simple Sortable List
Source: https://github.com/sortablejs/sortable/blob/master/index.html
Initializes a SortableJS instance for a simple list. Configure animation speed and the class for the ghost element.
```javascript
new Sortable(example1, {
animation: 150,
ghostClass: 'blue-background-class'
});
```
--------------------------------
### Initialize Sortable Instance with Options
Source: https://context7.com/sortablejs/sortable/llms.txt
Use `Sortable.create` to initialize drag-and-drop functionality on an HTML element. Configure behavior like grouping, sorting, animation, and event callbacks through the options object. Persist sort order using the `store` option with `localStorage`.
```javascript
import Sortable from 'sortablejs';
const list = document.getElementById('my-list');
const sortable = Sortable.create(list, {
// Grouping: allow dragging between lists with the same group name
group: {
name: 'shared',
pull: true, // allow items to be pulled out
put: true // allow items to be dropped in
},
sort: true, // enable sorting within the list
delay: 150, // ms before drag starts (useful on touch)
delayOnTouchOnly: true, // apply delay only for touch events
touchStartThreshold: 3, // px of movement before drag cancels delay
disabled: false, // set true to temporarily disable
animation: 200, // ms CSS animation speed for reordering
easing: 'cubic-bezier(1, 0, 0, 1)', // animation easing function
handle: '.drag-handle', // CSS selector for the drag handle
filter: '.no-drag', // CSS selector for elements that cannot be dragged
preventOnFilter: true, // call preventDefault on filtered elements
draggable: '.item', // CSS selector for draggable children
dataIdAttr: 'data-id', // attribute used by toArray()
ghostClass: 'sortable-ghost', // class on drop placeholder
chosenClass: 'sortable-chosen', // class on chosen (mousedown) item
dragClass: 'sortable-drag', // class on the dragging item
swapThreshold: 0.65, // fraction of target that triggers swap (0–1)
invertSwap: false, // always use inverted swap zone
forceFallback: false, // force touch fallback even on desktop
fallbackClass: 'sortable-fallback',
fallbackOnBody: false, // append fallback ghost to document.body
fallbackTolerance: 3, // px mouse must move before drag starts (fallback)
dragoverBubble: false,
removeCloneOnHide: true, // remove clone from DOM when hidden
emptyInsertThreshold: 5, // px from empty sortable to allow insertion
// Persist sort order with localStorage
store: {
get(sortable) {
const order = localStorage.getItem(sortable.options.group.name);
return order ? order.split('|') : [];
},
set(sortable) {
const order = sortable.toArray();
localStorage.setItem(sortable.options.group.name, order.join('|'));
}
},
// Events
onChoose(evt) { console.log('chosen:', evt.item); },
onUnchoose(evt) { console.log('unchosen:', evt.item); },
onStart(evt) { console.log('drag started, old index:', evt.oldIndex); },
onEnd(evt) {
console.log(`moved from ${evt.oldIndex} to ${evt.newIndex}`);
console.log('source list:', evt.from);
console.log('target list:', evt.to);
console.log('clone:', evt.clone);
console.log('pull mode:', evt.pullMode); // 'clone' | true
},
onAdd(evt) { console.log('item added from another list'); },
onUpdate(evt) { console.log('order changed within same list'); },
onSort(evt) { console.log('any change: add/update/remove'); },
onRemove(evt) { console.log('item removed to another list'); },
onFilter(evt) { console.log('filtered element clicked:', evt.item); },
onMove(evt, originalEvent) {
// Return false to cancel, -1 to insert before, 1 to insert after, true/void for default
if (evt.related.classList.contains('locked')) return false;
return true;
},
onClone(evt) { console.log('cloned:', evt.item, '→', evt.clone); },
onChange(evt) { console.log('dragging element now at index:', evt.newIndex); }
});
```
--------------------------------
### Initialize Sortable List with Thresholds
Source: https://github.com/sortablejs/sortable/blob/master/index.html
Sets up SortableJS with custom swap thresholds and inversion. `swapThreshold` controls how close an item must be to another to trigger a swap, and `invertSwap` reverses the swap behavior.
```javascript
new Sortable(example7, {
swapThreshold: 1,
invertSwap: true,
animation: 150
});
```
--------------------------------
### Basic Sortable Functionality with HTML5 Drag'n'Drop
Source: https://github.com/sortablejs/sortable/wiki/Sorting-with-the-help-of-HTML5-Drag'n'Drop-API
This JavaScript function enables drag-and-drop sorting for list items. It handles drag start, drag over, and drag end events to reorder elements. The `onUpdate` callback is invoked after sorting.
```javascript
function sortable(rootEl, onUpdate) {
var dragEl;
// Making all siblings movable
[].slice.call(rootEl.children).forEach(function (itemEl) {
itemEl.draggable = true;
});
// Function responsible for sorting
function _onDragOver(evt) {
evt.preventDefault();
evt.dataTransfer.dropEffect = 'move';
var target = evt.target;
if (target && target !== dragEl && target.nodeName == 'LI') {
// Sorting
rootEl.insertBefore(dragEl, target.nextSibling || target);
}
}
// End of sorting
function _onDragEnd(evt){
evt.preventDefault();
dragEl.classList.remove('ghost');
rootEl.removeEventListener('dragover', _onDragOver, false);
rootEl.removeEventListener('dragend', _onDragEnd, false);
// Notification about the end of sorting
onUpdate(dragEl);
}
// Sorting starts
rootEl.addEventListener('dragstart', function (evt){
dragEl = evt.target; // Remembering an element that will be moved
// Limiting the movement type
evt.dataTransfer.effectAllowed = 'move';
evt.dataTransfer.setData('Text', dragEl.textContent);
// Subscribing to the events at dnd
rootEl.addEventListener('dragover', _onDragOver, false);
rootEl.addEventListener('dragend', _onDragEnd, false);
setTimeout(function () {
// If this action is performed without setTimeout, then
// the moved object will be of this class.
dragEl.classList.add('ghost');
}, 0)
}, false);
}
// Using
sortable(document.getElementById('list'), function (item) {
console.log(item);
});
```
--------------------------------
### Store Sortable Order with LocalStorage
Source: https://github.com/sortablejs/sortable/blob/master/README.md
Saves and restores the order of sortable elements using localStorage. The `get` method retrieves the order, and the `set` method saves it on drag end. Ensure the `group` option is configured with a `name` for this to work.
```html
order
save
restore
```
```javascript
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('|'));
}
}
})
```
--------------------------------
### Mount AutoScroll Plugin
Source: https://github.com/sortablejs/sortable/blob/master/plugins/AutoScroll/README.md
Import and mount the AutoScroll plugin to enable its functionality. This is required before using any AutoScroll options.
```javascript
import { Sortable, AutoScroll } from 'sortablejs';
Sortable.mount(new AutoScroll());
```
--------------------------------
### SortableJS Import Patterns (ESM)
Source: https://context7.com/sortablejs/sortable/llms.txt
Import SortableJS using different builds (default, core, complete) or cherrypick specific plugins for modularity. Ensure the correct path is used for the desired build.
```javascript
// Default build (includes AutoScroll + OnSpill plugins)
import Sortable from 'sortablejs';
// Core build (no default plugins — smallest bundle)
import Sortable from 'sortablejs/modular/sortable.core.esm.js';
// Complete build (all plugins pre-mounted)
import Sortable from 'sortablejs/modular/sortable.complete.esm.js';
// Cherrypick extra plugins from default build
import Sortable, { MultiDrag, Swap } from 'sortablejs';
Sortable.mount(new MultiDrag(), new Swap());
// Cherrypick default plugins from core build
import Sortable, { AutoScroll } from 'sortablejs/modular/sortable.core.esm.js';
Sortable.mount(new AutoScroll());
```
--------------------------------
### sortable.closest(el[, selector])
Source: https://context7.com/sortablejs/sortable/llms.txt
A utility method to find the closest ancestor element matching a given selector, starting from a specified element and searching within the sortable's root. Defaults to the draggable element selector if no selector is provided.
```APIDOC
## sortable.closest(el[, selector]) — Traverse up to matching ancestor
Utility to find the closest ancestor element (within the sortable's root) matching `selector`. Defaults to `options.draggable` if no selector is given.
```js
const sortable = Sortable.create(document.getElementById('list'), {
draggable: 'li'
});
document.getElementById('list').addEventListener('click', (evt) => {
// Find closest draggable item from click target
const item = sortable.closest(evt.target);
if (item) {
console.log('clicked item:', item.textContent);
}
// Find closest element matching a custom selector
const row = sortable.closest(evt.target, '.data-row');
console.log('enclosing data row:', row);
});
```
```
--------------------------------
### Custom Plugin API — Extend Sortable with Plugins
Source: https://context7.com/sortablejs/sortable/llms.txt
Create custom plugins by defining constructor functions that intercept Sortable's lifecycle events. Mount plugins using `Sortable.mount()` and enable them via custom options.
```javascript
import Sortable from 'sortablejs';
// A plugin that logs drag operations with timestamps
function LoggerPlugin(sortable, el, options) {
this.defaults = {
enableLogging: false // custom option; user enables via { enableLogging: true }
};
}
LoggerPlugin.prototype = {
dragStart({ dragEl }) {
if (!this.options.enableLogging) return;
console.log(`[${Date.now()}] Drag started:`, dragEl.textContent);
},
drop({ dragEl, originalEvent }) {
if (!this.options.enableLogging) return;
console.log(`[${Date.now()}] Dropped:`, dragEl.textContent);
},
nulling() {
// cleanup after drag ends
}
};
LoggerPlugin.pluginName = 'enableLogging'; // option name to enable plugin
LoggerPlugin.initializeByDefault = true; // init on every Sortable instance
// Optionally, expose utils on Sortable.utils
LoggerPlugin.utils = {
getLogCount() { return window._sortableLogCount || 0; }
};
Sortable.mount(LoggerPlugin);
const sortable = Sortable.create(document.getElementById('list'), {
enableLogging: true, // activates the plugin
animation: 150
});
```
--------------------------------
### new Sortable(el, options)
Source: https://context7.com/sortablejs/sortable/llms.txt
Initializes a new Sortable instance on a given HTML element with specified options. It throws an error if the provided element is not a valid HTMLElement.
```APIDOC
## new Sortable(el, options) — Constructor
Direct constructor equivalent to `Sortable.create`. Throws if `el` is not a valid `HTMLElement`.
```js
import Sortable from 'sortablejs';
const el = document.querySelector('#task-list');
try {
const sortable = new Sortable(el, {
animation: 150,
ghostClass: 'ghost'
});
} catch (e) {
console.error('Sortable init failed:', e);
// e.g. "Sortable: `el` must be an HTMLElement, not [object Undefined]"
}
```
```
--------------------------------
### Initialize Sortable List for Cloning
Source: https://github.com/sortablejs/sortable/blob/master/index.html
Sets up SortableJS instances where items can be cloned from one list to another. The `pull: 'clone'` option ensures the original item remains.
```javascript
new Sortable(example3Left, {
group: {
name: 'shared',
pull: 'clone'
},
animation: 150
});
new Sortable(example3Right, {
group: {
name: 'shared',
pull: 'clone'
},
animation: 150
});
```
--------------------------------
### Mount OnSpill Plugins
Source: https://github.com/sortablejs/sortable/blob/master/plugins/OnSpill/README.md
Import and mount the OnSpill plugins for SortableJS. These are included in default builds.
```javascript
import { Sortable, OnSpill } from 'sortablejs/modular/sortable.core.esm';
Sortable.mount(OnSpill);
```
--------------------------------
### Store Configuration
Source: https://github.com/sortablejs/sortable/blob/master/README.md
Configuration for saving and restoring the order of sortable elements using localStorage.
```APIDOC
## Store Configuration
### Description
Configuration for saving and restoring the order of sortable elements using localStorage.
### Options
* **store.get(sortable)**: A function that retrieves the order of elements. Called once during initialization.
* Returns: `Array` - The order of elements.
* **store.set(sortable)**: A function that saves the order of elements. Called on `onEnd` (when the item is dropped).
* Parameters:
* **sortable** (Sortable) - The Sortable instance.
```
--------------------------------
### Import Default SortableJS
Source: https://github.com/sortablejs/sortable/blob/master/README.md
Import the default SortableJS module into your project.
```javascript
import Sortable from 'sortablejs';
```
--------------------------------
### Mounting the MultiDrag Plugin
Source: https://github.com/sortablejs/sortable/blob/master/plugins/MultiDrag/README.md
To use the MultiDrag plugin, you need to import it and then mount it to SortableJS.
```APIDOC
## Mounting
```js
import { Sortable, MultiDrag } from 'sortablejs';
Sortable.mount(new MultiDrag());
```
```
--------------------------------
### Sortable.create(el, options)
Source: https://context7.com/sortablejs/sortable/llms.txt
Initializes a Sortable instance on a given HTML container element. This method accepts a comprehensive options object to control drag behavior, grouping, animation, filtering, and event callbacks. It returns a Sortable instance.
```APIDOC
## Sortable.create(el, options)
### Description
Initializes a Sortable instance on a given HTML container element. Accepts a rich options object controlling all drag behavior, grouping, animation, filtering, and event callbacks. Returns a `Sortable` instance.
### Parameters
#### Path Parameters
- **el** (HTMLElement) - Required - The HTML element to make sortable.
- **options** (Object) - Optional - Configuration options for the Sortable instance.
### Options
- **group** (Object | String) - Configuration for grouping sortable lists. Can be a string name or an object with `name`, `pull`, and `put` properties.
- **name** (String) - The name of the group.
- **pull** (Boolean | String | Object) - Whether items can be pulled from this list.
- **put** (Boolean | String | Object) - Whether items can be put into this list.
- **sort** (Boolean) - Enable sorting within the list. Defaults to `true`.
- **delay** (Number) - Delay in milliseconds before drag starts. Useful on touch devices. Defaults to `0`.
- **delayOnTouchOnly** (Boolean) - Apply delay only for touch events. Defaults to `false`.
- **touchStartThreshold** (Number) - Pixels of movement before drag cancels delay. Defaults to `0`.
- **disabled** (Boolean) - Set to `true` to temporarily disable sorting. Defaults to `false`.
- **animation** (Number) - CSS animation speed in milliseconds for reordering. Defaults to `0`.
- **easing** (String) - Animation easing function. Defaults to `'cubic-bezier(1, 0, 0, 1)'`.
- **handle** (String) - CSS selector for the drag handle. If specified, only elements matching this selector can initiate a drag.
- **filter** (String | Function) - CSS selector or function to filter elements that cannot be dragged.
- **preventOnFilter** (Boolean) - Call `preventDefault` on filtered elements. Defaults to `true`.
- **draggable** (String) - CSS selector for draggable children. Defaults to `':scope > *'`.
- **dataIdAttr** (String) - Attribute used by `toArray()` to identify items. Defaults to `'data-id'`.
- **ghostClass** (String) - Class applied to the drop placeholder element. Defaults to `'sortable-ghost'`.
- **chosenClass** (String) - Class applied to the chosen (mousedown) item. Defaults to `'sortable-chosen'`.
- **dragClass** (String) - Class applied to the dragging item. Defaults to `'sortable-drag'`.
- **swapThreshold** (Number) - Fraction of target that triggers swap (0–1). Defaults to `0`.
- **invertSwap** (Boolean) - Always use inverted swap zone. Defaults to `false`.
- **forceFallback** (Boolean) - Force touch fallback even on desktop. Defaults to `false`.
- **fallbackClass** (String) - Class applied to the fallback ghost element.
- **fallbackOnBody** (Boolean) - Append fallback ghost to `document.body`. Defaults to `false`.
- **fallbackTolerance** (Number) - Pixels mouse must move before drag starts (fallback). Defaults to `5`.
- **dragoverBubble** (Boolean) - Allow dragover events to bubble. Defaults to `false`.
- **removeCloneOnHide** (Boolean) - Remove clone from DOM when hidden. Defaults to `true`.
- **emptyInsertThreshold** (Number) - Pixels from empty sortable to allow insertion. Defaults to `5`.
- **store** (Object) - Interface for persisting sort order.
- **get** (Function) - Function to retrieve the current order.
- **set** (Function) - Function to save the new order.
### Events
- **onChoose(evt)**: Called when an item is chosen.
- **onUnchoose(evt)**: Called when an item is unchosen.
- **onStart(evt)**: Called when dragging starts.
- **onEnd(evt)**: Called when dragging ends.
- **onAdd(evt)**: Called when an item is added from another list.
- **onUpdate(evt)**: Called when the order changes within the same list.
- **onSort(evt)**: Called on any change (add/update/remove).
- **onRemove(evt)**: Called when an item is removed to another list.
- **onFilter(evt)**: Called when a filtered element is clicked.
- **onMove(evt, originalEvent)**: Called when an item is moved. Return `false` to cancel, `-1` to insert before, `1` to insert after, `true`/`void` for default behavior.
- **onClone(evt)**: Called when an item is cloned.
- **onChange(evt)**: Called when the dragging element is at a new index.
### Request Example
```javascript
import Sortable from 'sortablejs';
const list = document.getElementById('my-list');
const sortable = Sortable.create(list, {
group: {
name: 'shared',
pull: true,
put: true
},
sort: true,
delay: 150,
animation: 200,
handle: '.drag-handle',
filter: '.no-drag',
draggable: '.item',
ghostClass: 'sortable-ghost',
chosenClass: 'sortable-chosen',
dragClass: 'sortable-drag',
store: {
get(sortable) {
const order = localStorage.getItem(sortable.options.group.name);
return order ? order.split('|') : [];
},
set(sortable) {
const order = sortable.toArray();
localStorage.setItem(sortable.options.group.name, order.join('|'));
}
},
onEnd(evt) {
console.log(`moved from ${evt.oldIndex} to ${evt.newIndex}`);
},
onMove(evt, originalEvent) {
if (evt.related.classList.contains('locked')) return false;
return true;
}
});
```
### Response
Returns a `Sortable` instance.
```
--------------------------------
### Initialize Sortable Instance with Constructor
Source: https://context7.com/sortablejs/sortable/llms.txt
Use the `new Sortable()` constructor to initialize a Sortable instance on an HTMLElement. It throws an error if the provided element is not a valid HTMLElement. Ensure the `Sortable` module is imported.
```javascript
import Sortable from 'sortablejs';
const el = document.querySelector('#task-list');
try {
const sortable = new Sortable(el, {
animation: 150,
ghostClass: 'ghost'
});
} catch (e) {
console.error('Sortable init failed:', e);
// e.g. "Sortable: `el` must be an HTMLElement, not [object Undefined]"
}
```
--------------------------------
### Import Modular Core SortableJS
Source: https://github.com/sortablejs/sortable/blob/master/README.md
Import the core SortableJS module, excluding default plugins, for a smaller footprint.
```javascript
import Sortable from 'sortablejs/modular/sortable.core.esm.js';
```
--------------------------------
### Import Complete SortableJS
Source: https://github.com/sortablejs/sortable/blob/master/README.md
Import the complete SortableJS module, including all plugins, for full functionality.
```javascript
import Sortable from 'sortablejs/modular/sortable.complete.esm.js';
```
--------------------------------
### Basic SortableJS Initialization
Source: https://github.com/sortablejs/sortable/blob/master/README.md
Initialize SortableJS on an HTML element to enable drag-and-drop reordering for its children.
```html
item 1
item 2
item 3
```
```javascript
var el = document.getElementById('items');
var sortable = Sortable.create(el);
```
--------------------------------
### touchStartThreshold Option
Source: https://github.com/sortablejs/sortable/blob/master/README.md
Define the minimum pointer movement required to cancel delayed sorting, preventing unwanted triggers on sensitive touch screens.
```APIDOC
## touchStartThreshold Option
### Description
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.
### Parameters
- **touchStartThreshold**: `number` - Minimum pointer movement in pixels before delayed sorting is cancelled.
```
--------------------------------
### Sortable.mount
Source: https://github.com/sortablejs/sortable/blob/master/README.md
Mounts one or more Sortable plugins to extend its functionality.
```APIDOC
## Sortable.mount
### Description
Mounts one or more Sortable plugins to extend its functionality.
### Method
`Sortable.mount(plugin: ...SortablePlugin | SortablePlugin[])`
### Parameters
* **plugin** (...SortablePlugin | SortablePlugin[]) - A plugin or an array of plugins to mount.
```
--------------------------------
### Sortable.utils
Source: https://github.com/sortablejs/sortable/blob/master/README.md
A collection of utility functions for DOM manipulation, event handling, and element detection.
```APIDOC
## Sortable.utils
### Description
A collection of utility functions for DOM manipulation, event handling, and element detection.
### Methods
* **on(el: HTMLElement, event: String, fn: Function)**: Attaches an event handler.
* **off(el: HTMLElement, event: String, fn: Function)**: Removes an event handler.
* **css(el: HTMLElement)**: Returns an object with all CSS property values.
* **css(el: HTMLElement, prop: String)**: Returns the value of a specific CSS property.
* **css(el: HTMLElement, prop: String, value: String)**: Sets a specific CSS property.
* **css(el: HTMLElement, props: Object)**: Sets multiple CSS properties.
* **find(ctx: HTMLElement, tagName: String, iterator?: Function)**: Gets elements by tag name within a context.
* **bind(ctx: Mixed, fn: Function)**: Returns a new function with a fixed context.
* **is(el: HTMLElement, selector: String)**: Checks if an element matches a selector.
* **closest(el: HTMLElement, selector: String, ctx?: HTMLElement)**: Finds the closest ancestor element matching a selector.
* **clone(el: HTMLElement)**: Creates a deep copy of an element.
* **toggleClass(el: HTMLElement, name: String, state: Boolean)**: Adds or removes a CSS class.
* **detectDirection(el: HTMLElement)**: Detects the direction ('vertical' or 'horizontal') of an element.
* **index(el: HTMLElement, selector: String)**: Gets the index of an element within its parent among selected elements.
* **getChild(el: HTMLElement, childNum: Number, options?: Object, includeDragEl?: Boolean)**: Gets a draggable child element at a specific index.
* **expando**: `String` - Internal property name for Sortable instance on elements.
```
--------------------------------
### handle Option
Source: https://github.com/sortablejs/sortable/blob/master/README.md
Specify a selector for an element within each list item that acts as a drag handle, allowing the rest of the item to be selected.
```APIDOC
## handle Option
### Description
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.
### Parameters
- **handle**: `string` - A CSS selector for the drag handle element within each list item.
### Usage Example
```js
Sortable.create(el, {
handle: ".my-handle"
});
```
```
--------------------------------
### Configure AutoScroll Options
Source: https://github.com/sortablejs/sortable/blob/master/plugins/AutoScroll/README.md
Configure the AutoScroll plugin's behavior using various options when initializing Sortable. The `scroll` option enables the plugin, and others like `scrollSensitivity` and `scrollSpeed` fine-tune the scrolling experience.
```javascript
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
});
```
--------------------------------
### Initialize Sortable with Handle and Events
Source: https://github.com/sortablejs/sortable/wiki/Sorting-with-the-help-of-HTML5-Drag'n'Drop-API
Initializes SortableJS with custom drag handles and specifies which elements are draggable. It also includes an `onUpdate` event handler to capture when an item's position changes.
```javascript
// handle + event
var container = document.getElementById("multi");
new Sortable(container, {
handle: ".tile__title", // css-selector, which can be used to drag
draggable: ".tile", // css-selector of elements, which can be sorted
onUpdate: function (/**Event*/evt){
var item = evt.item; // a link to an element that was moved
}
});
```
--------------------------------
### Mounting the AutoScroll Plugin
Source: https://github.com/sortablejs/sortable/blob/master/plugins/AutoScroll/README.md
This snippet shows how to import and mount the AutoScroll plugin into SortableJS. It's a default plugin included in UMD and ESM builds.
```APIDOC
## Mounting AutoScroll
```js
import { Sortable, AutoScroll } from 'sortablejs';
Sortable.mount(new AutoScroll());
```
```
--------------------------------
### Sortable.create
Source: https://github.com/sortablejs/sortable/blob/master/README.md
Creates a new Sortable instance on a given HTML element with optional configuration options.
```APIDOC
## Sortable.create
### Description
Creates a new Sortable instance on a given HTML element with optional configuration options.
### Method
`Sortable.create(el: HTMLElement, options?: Object): Sortable`
### Parameters
* **el** (HTMLElement) - The HTML element to make sortable.
* **options** (Object) - Optional configuration object for the Sortable instance.
```