Multiple sortable lists with drag-and-drop transfer using jQuery UI

The other day, I was looking at a piece of code on a project I’m working on where we’re using a jQuery UI sortable┬ácontrol to allow the user to re-order the elements in the list by dragging them. We wanted to be able to add multiple levels of containers in the list, so sortables inside of sortables. This would also mean that the user would need to be able to drag elements in the list to another list existing inside of the list itself, which presents a lot of confusing code problems. After looking online, there were a lot of confusing solutions which involved handling drag and drop events using draggable and droppable┬ácomponents. I didn’t have any luck with these, so I continued on and reviewed the documentation for sortable to find this gem: the connectWith┬áproperty. You give it a selector, and it lets the elements in your sortable list be drag-and-droppable to any other sortable list that matches the selector. Here is a simple example:

$('.my-sortable').sortable({ connectWith: ".my-sortable" });

In this example, any element on the page with the class “my-sortable” becomes a sortable list whose items can be drag-and-dropped to any other sortable list using this class. It’s yet another example of a jQuery one-liner that takes something complicated to do by hand and turns it into an elegant piece of code.