Web Development with jQuery®

(Elliott) #1

Implementing Drag and Drop (^) ❘ 289


Event Setup


Now that you have defi ned these two jQuery plugins, you set up the events that you need to imple-
ment the drag-and-drop API.

$(document).ready(
function()
{
$(document).on(
'mousedown.finder',
'div.finderDirectory, div.finderFile',
function(event)
{
$(this).enableDragAndDrop();

$('div.finderIconSelected')
.removeClass('finderIconSelected');

$('span.finderDirectoryNameSelected')
.removeClass('finderDirectoryNameSelected');

$(this).find('div.finderIcon')
.addClass('finderIconSelected');

$(this).find('div.finderDirectoryName span')
.addClass('finderDirectoryNameSelected');
}
);

The fi rst event that you create is a mousedown event that enables drag-and-drop functionality on
each <div> element with the class names finderDirectory and finderFile. Because it uses the on()
method, it is applied automatically when new <div> elements with those class names are added to
the DOM. You’ll expand on the concept of dynamically applying events to take care of the fi le or
folders added to the folder you’re viewing later in this chapter in Example 11-2. The mousedown event
is applied with an event namespace, fi nder, which you learned about in Chapter 3, “Events.” Using
jQuery’s event namespaces allows you more control over binding and unbinding event handlers.
Using the namespace you can unbind only the events in the fi nder namespace, if wanted, without
affecting events in other namespaces.

The next thing you do is to begin applying drag-and-drop events to each fi le and folder
<div> element. Along with the CSS property WebkitUserDrag, the HTML attribute draggable,
and the dragDrop() method, the application of these events controls what happens when a
user drags and drops elements. The drag-and-drop events fi re in the following order on the
element dragged:


  1. dragstart

  2. drag

  3. dragend


The drag-and-drop events fi re in the following order on the drop element:


http://www.it-ebooks.info

Free download pdf