Lesson 1: Dragging and dropping CHAPTER 13 511
The following code is placed in the MicroScramble.js file and shows the use of the drag-
start and dragend events to change the style of the item being dragged until the dragging
ends.
/// <reference path="jquery-1.8.3.js" />
var $draggedItem;
$(document).ready(function () {
$('.item').on('dragstart', dragging);
$('.item').on('dragend', draggingEnded);
});
function dragging(e) {
$(e.target).addClass('dragging');
$draggedItem = $(e.target);
}
function draggingEnded(e) {
$(e.target).removeClass('dragging');
}
This example uses the document ready function in jQuery to subscribe to the dragstart
and dragend events on all elements that have the CSS class item assigned. The dragging func-
tion adds the dragging CSS class when the dragging starts and then sets the $draggedItem
with the value of the item being dragged. The draggingEnded function removes the dragging
CSS class.
In the MicroScramble.css file, the dragging CSS rule is defined as follows.
.dragging {
background-color: yellow;
}
In this example, the background of the dragged item changes to yellow until the dragging
stops.
Dropping
After dragging, the drop must be made operational. The following events are based on the
drop target.
■■dragenter Triggers when the drag enters a drop zone
■■dragover Triggers continuously as the element is dragged over the drop zone
■■dragleave Triggers when the dragged item leaves a drop zone
■■drop Triggers when the dragged item is dropped
The dragenter and dragover events default to rejecting dragged items, which is why you
can’t currently drop an item. You can enable dropping by cancelling the default action on
these events.