jqueryui posts

JQuery UI Droppable and Handling Multiple Draggable Types per Droppable

JQuery UI Draggable and Droppable make it fairly easy to implement dragondrop on a web page. There are some things that are not easy to do with it though. One example is having a droppable accept multiple types of draggables with different responses depending on type, especially when added at different times (for instance, being attached by separate objects/scripts). The way JQuery UI is set up, only one droppable behavior set can be attached to an element, so doing

element.droppable({accept: ".type1",...});
element.droppable({accept: ".type2",...});

simply replaces the “.type1” options with the “.type2” options.

In a recent project, I needed multiple draggable types per droppable, so I created an object class to handle adding a new “accept” type and associated events to an element that is already a droppable. I do this using duck punching to overwrite the original event callbacks. The wrapper callback checks the draggable element to see if it matches the new “accept” value. If so, it runs the new callback, otherwise it runs the original callback. Every time a new set of droppable options is applied, a new wrapper callback is created that calls the previous, so that no functionality is lost. Perhaps not as efficient as a single function with an if/switch tree, but that would not be feasible for this use case.

Continue reading post "JQuery UI Droppable and Handling Multiple Draggable Types per Droppable"