What is sortablejs?
The sortablejs package is a JavaScript library for creating reorderable drag-and-drop lists on modern web browsers and touch devices. It does not require any jQuery dependency and provides a simple API for developers to enable sortable functionality in their web applications.
What are sortablejs's main functionalities?
Basic list sorting
This code snippet enables drag-and-drop sorting on the list with the ID 'items'. It creates a Sortable instance that allows list items to be reordered by dragging.
var el = document.getElementById('items');
var sortable = Sortable.create(el);
Grouping and sharing between lists
This code snippet connects two lists, allowing items to be dragged from one list to another. Both lists share the same 'group' property, enabling the sharing of items.
var el1 = document.getElementById('list1');
var el2 = document.getElementById('list2');
Sortable.create(el1, {
group: 'shared',
animation: 150
});
Sortable.create(el2, {
group: 'shared',
animation: 150
});
Saving and restoring list order
This code snippet demonstrates how to save the order of the list to localStorage and restore it when the page is reloaded. The 'store' option is used to provide custom 'get' and 'set' functions for storing the order.
var el = document.getElementById('items');
var sortable = Sortable.create(el, {
store: {
get: function (sortable) {
var order = localStorage.getItem(sortable.options.group.name);
return order ? order.split('|') : [];
},
set: function (sortable) {
var order = sortable.toArray();
localStorage.setItem(sortable.options.group.name, order.join('|'));
}
}
});
Customizing drag handle
This code snippet shows how to specify a custom drag handle for list items. Only elements with the class 'my-handle' will be draggable.
var el = document.getElementById('items');
var sortable = Sortable.create(el, {
handle: '.my-handle',
animation: 150
});
Other packages similar to sortablejs
react-beautiful-dnd
A React-centric drag-and-drop library that provides a powerful, opinionated solution for building complex drag-and-drop interfaces. It differs from sortablejs in that it is built specifically for React and offers a more extensive set of features for React developers.
dragula
A simple drag-and-drop library that is similar to sortablejs but with a focus on simplicity and touch support. It provides a minimal API and is easy to get started with, but it may not have as many features as sortablejs.
dnd-kit
A modern drag-and-drop toolkit for building accessible and performant drag-and-drop interfaces. It is framework-agnostic and offers a comprehensive set of utilities for building complex drag-and-drop systems. It is more modular and flexible than sortablejs but may require more setup.