1. Events
  2. Before Swap Event

When the user is about to swap the item, whether on hover or drop, Swapy fires an event where you can prevent the swap if you want to.

If you return true from the event handler, it will be allowed; otherwise, it will be prevented.

You can listen to that event using swapy.onBeforeSwap().

swapy.onBeforeSwap((event) => {
  console.log(event)
  return true
})

The event object contains the following:

  • fromSlot: the id of the slot where the item was dragged from.
  • toSlot: the id of the slot the item was dragged into.
  • draggingItem: the id of the item being dragged.
  • swappedWithItem: the id of the item it was swapped with.

Event object example

In this example, I’m preventing the swap if the target slot has the id foo. But you can write any condition you want.

swapy.onBeforeSwap((event) => {
  console.log(event.fromSlot)
  // 'foo'

  console.log(event.toSlot)
  // 'bar'

  console.log(event.draggingItem)
  // 'b'

  console.log(event.swappedWithItem)
  // 'a'

  return event.toSlot !== 'foo'
})

Demo

To see this event in action, use the demo below, open the dev console, and check the event object logged before each swap. (All swaps are allowed in this example.)

A
B
C
D