button, and new index cards get added to the user interface. Since we set the
contenteditable attribute, we can click on each one and set its text.
Making the Cards Sortable
Before we write the code to make the cards sortable, let’s go over how it’s
going to work. When we drag one card over another card, the card we dragged
will be inserted after the card we drag it over. To do that, we’ll pass the ID of
the card we’re dragging to the element we’re dropping the card on. When the
card is dropped, we’ll use jQuery to locate the original element by its ID and
move it into the proper position.
The Drag and Drop specification supports the following events:
Event Description
ondragstart Fires when the user starts dragging the object
ondragend Fires when the user stops dragging the object for any reason
ondragenter Fires when a draggable element is moved into a drop listener
ondragover Fires when the user drags an element over a drop listener
ondragleave Fires when the user drags an element out of a drop listener
ondrop Fires when the user drops an element into a drop listener
Fires when the user drags an element anywhere; fires con-
stantly but can give x- and y-coordinates of the mouse cursor
ondrag
We’ll need to worry about only a couple of these as we build out our code for
this project.
We’ll start by creating a new function called createDragAndDropEvents(), which will
hold all of the event handlers we need for drag-and-drop functionality. The
first thing we’ll do with this method is use jQuery to grab the cards region of
the page. This is the region where the cards are being inserted.
html5_dragdrop/javascripts/cards.js
varcreateDragAndDropEvents=function(){
varcards= $("#cards");
};
Within this method we’ll define our events. When the user starts dragging a
card, the ondragstart() method will fire. We’ll need create an event handler for
that, and inside of that handler we’ll grab the card’s ID and store it in the
dataTransfer object. This object holds the data that’s being dragged from one
element to another. We use the setData() method for that.
Chapter 10. Creating Interactive Web Applications • 234
Download from Wow! eBook <www.wowebook.com> report erratum • discuss