Meet Swapy, a framework-agnostic tool that converts any layout into a drag-to-swap one with just a few lines of code.
1. Install
Use your favorite package manager to install it.
npm install swapy
Or get it from CDN.
2. Using Swapy
Below, I'm showing you a simple layout, but yours can be as complex as you want it to be.
Specify Slots and Items
- To specify a slot, give its element
data-swapy-slot="anyUniqueNameYouWant"
. Each slot can only contain a single item. Items are what you drag and drop. - To mark an element as an item, add this data attribute:
data-swapy-item="anyUniqueNameYouWant"
.
By default, items are draggable from any spot. You can specify a handle by adding an element with data-swapy-handle
(see content-b below).
You can customize the slot you are currently selecting by styling [data-swapy-highlighted]
in your CSS.
</div>
</div>
Use Swapy
Get the container element that contains your slots and items, and pass it to createSwapy()
. By default, it will use `dynamic` animation. You can change it using the animation config option.
import { createSwapy } from 'swapy'
const container = document.querySelector('.container')
const swapy = createSwapy(container, { animation: 'dynamic' // or spring or none })
// You can disable and enable it anytime you want swapy.enable(true)
3. Listening to Events
You can listen to swap events to do things like storing the new order. To make it more convenient for you, the swap event returns three versions of the new order: map, object, and array.
import { createSwapy } from 'swapy'
const container = document.querySelector('.container')
const swapy = createSwapy(container)
swapy.onSwap((event) => { console.log(event.data.object); console.log(event.data.array); console.log(event.data.map);
// event.data.object: // { // 'foo': 'a', // 'bar': 'b', // 'baz': 'c' // }
// event.data.array: // [ // { slot: 'foo', item: 'a' }, // { slot: 'bar', item: 'b' }, // { slot: 'baz', item: 'c' } // ]
// event.data.map: // Map(3) { // 'foo' => 'a', // 'bar' => 'b', // 'baz' => 'c' // } })