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.

Advertisements

Tutorial: Intro to jQuery

My wife was on her Facebook the other evening when she stumbled on a post from a friend of hers from High School: “I give the &*#$ up…” The friend was in a class about JavaScript and jQuery, and with the end of the semester closing in was struggling. She was willing to learn, but hadn’t been given the proper instruction so that the pieces made sense together. So, I spent some time online with her helping her understand how to use these tools to get the job done, and along the way I discovered some teaching strategies and examples that worked and some that didn’t. I took what I told her, cleaned it up, and produced a little online tutorial for getting started with jQuery. Go ahead and check it out here:

[Open Tutorial]

Cheers!

Steven