Web Development with jQuery®

(Elliott) #1

Designating Drop Zones for Draggable Elements (^) ❘ 331
DESIGNATING DROP ZONES FOR DRAGGABLE ELEMENTS
Typically when you implement dragging on elements in your document, you want to designate
somewhere for the elements being dragged to be dropped. jQuery UI provides another plugin for
handling the drop portion of this; it is called Droppable. The jQuery UI Droppable plugin enables
you to create and manipulate a variety of things associated with dropping one element onto another,
including what happens while you drag one element over a drop zone and what happens when a
drop takes place. jQuery allows you to have precision control over drag-and-drop, which lets you
create a basic drag-and-drop implementation or a polished drag-and-drop implementation.
As you’ve already seen with the Draggable API, jQuery UI provides a concise, easy-to-use API for
handling the drop side. To make an element into a droppable element, all you have to do is make
a selection and call the droppable() method with the appropriate options, just as you did with the
draggable() method. Options are provided via an object literal consisting of key, value pairs. The
following example shows you what a droppable implementation looks like in the context of the
Finder clone you’ve been building throughout this chapter:
$('div.finderDirectory')
.draggable({
helper: 'clone',
opacity: 0.5
})
.droppable({
accept: 'div.finderDirectory',
hoverClass: 'finderDirectoryDrop'
});
In the preceding code, you have a basic example implementation of the Droppable API. Each


element with the class name finderDirectory is made into a drop zone so that any directory can be
dragged and dropped onto any other directory. To make the drop portion function properly, you
pass some options to the droppable() method. The accept option lets you specify a selector that will
be used to match what elements you want to allow to be dropped onto the drop zone. In this case,
you want to allow only
elements with the class name finderDirectory to be dropped. Using
this fi lter, you can add other drag-and-drop functionality within the same document without having
confl ict between different drag-and-drop implementations.
The hoverClass option allows you to change the style of the drop zone as a draggable element is
dragged over the droppable element. You simply specify a class name as the value and then set up
the appropriate styles in your style sheet.
In the following example (Example 12-2), you take the basic concept of the Droppable API that was
demonstrated and apply the droppable() method to the Finder clone you’ve been building.
<!DOCTYPE HTML>




content='application/xhtml+xml; charset=utf-8' />

Finder

[http://www.it-ebooks.info](http://www.it-ebooks.info)