Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

512 CHAPTER 13 Drag and drop


The drop event removes the dropped item from the document object model (DOM) and
then adds it back to the DOM at the drop zone location. The following code subscribes to the
dragenter, dragover, and drop events.
/// <reference path="jquery-1.8.3.js" />

var $draggedItem;

$(document).ready(function () {
$('.item').on('dragstart', dragging);
$('.item').on('dragend', draggingEnded);
$('.hole').on('dragenter', preventDefault);
$('.hole').on('dragover', preventDefault);
$('.hole').on('drop', dropItem);
});

function dragging(e) {
$(e.target).addClass('dragging');
$draggedItem = $(e.target);
}

function draggingEnded(e) {
$(e.target).removeClass('dragging');
}

function preventDefault(e) {
e.preventDefault();
}

function dropItem(e) {
var hole = $(e.target);
if (hole.hasClass('hole') && hole.children().length == 0) {
$draggedItem.detach();
$draggedItem.appendTo($(e.target));
}
}

In this example, the document ready function has added statements to subscribe to drag-
enter, dragover, and drop. Notice that dragenter and dragover call the same preventDefault
function, which prevents the rejection of the dragged items.
The drop event calls the dropItem function. In dropItem, a jQuery object is created from
e.target, which is the drop target, and is assigned to a hole variable. The if statement checks
whether the drop target has the hole CSS class. This is necessary because you might drop
something on top of an item instead of on a hole. When the item is in a hole, the drop event
bubbles up and executes the drop event on the hole. If the drop target is a hole, the code
checks whether there are children; if there is a child, this hole already has an item, and you
shouldn’t be able to drop. If the drop target is a hole with no children, jQuery detaches the
dragged item from the DOM and then appends draggedItem to the drop target. Figure 13-3
shows the item when it is being dragged and when it is dropped.
Free download pdf