Tag Archives: sortable

jQuery UI draggable into multiple sortables with remove

jQuery UI is a useful if somewhat large library and we use it in some of our backend stuff where page load times aren’t quite so important.

One of it’s cool features is the ability to have one or more sortable containers that can have items dropped onto them either from an external draggable element or from another connected sortable container.

But have you ever tried to remove an item from one of a group of connected sortable containers?

This should be a piece of cake to do but unfortunately the sortable over and out events don’t play nicely together at all when you have multiple connected sortable containers. Go and try it for yourself, then come back to see a quick and easy way to do it.

A simple trick I’ve found to solve this problem is to make your sortable containers droppable also, and to use the droppable over and out events. You’ll need the approriate references to the jQuery and jQuery UI libraries & CSS of course.

A few additional lines of code to make the containers droppable will now allow you to:

  • drag and drop external draggable items onto any of the sortable containers
  • drag and drop items between any of the sortable containers
  • completely remove items from all of the sortable containers by dragging and dropping them away from a sortable container (ie anywhere else on the page)

The following code is stripped down to the essentials (although you may or may not need the draggable clone helper depending on your application) and shows how to do this:

var remove_me = false;

$('.your_external_draggable_element').draggable({
  connectToSortable: ".your_sortable_container",
  helper: "clone",
});

$('.your_sortable_container').droppable({
  over: function(){
    remove_me = false;
  },
  out: function(){
    remove_me = true;
  }
}).sortable({
  tolerance: "pointer",
  connectWith: '.your_sortable_container',
  stop: function(event, ui){
    if (remove_me){
      ui.item.remove();
    }
  },
});

Do you know of any simpler or better ways? If so, let us know in the comments…