To do all of this, we want to watch the ondragstart() event on each card. Adding
event handlers to each card creates a lot of handlers, which could impact
performance, so we use jQuery to create delegated events. We create the event
on the cards region of the page, but tell jQuery to delegate the event to an
individual card. This event will get registered for new cards the user adds
later, too.
Inside the createDragAndDropEvents() function, add this code to create the event
handler and store the card’s ID:
html5_dragdrop/javascripts/cards.js
Line 1 cards.on("dragstart",".card",function(event){
2
});
event.originalEvent.dataTransfer.setData('text', this.id);
3
The setData() method requires both the data type and the data we want to send.
Since we’re sending only the element’s ID, we’re using plain text for the data
type. setData() can accept any MIME type as its first argument, but for maximum
compatibility with older browsers, we’re using the keyword text here, which
the HTML5 specification supports and maps to the MIME type of text/plain. At
the time of publication, Internet Explorer 10 is the only modern browser that
doesn’t understand MIME types here.
When we drop the card on top of another card, we want the card we dropped
to be placed right after the card we drop it on. We do that with the ondrop()
event, which we’ll create in the same fashion as the ondragstart() event:
html5_dragdrop/javascripts/cards.js
Line 1 cards.on("drop",".card",function(event){
2 event.preventDefault();
3 varid = event.originalEvent.dataTransfer.getData('text');
4 varoriginalCard= $("#"+ id);
(^5) originalCard.insertAfter(this);
6
});
return(false);
7
From the dataTransfer object we fetch the ID of the element we dropped, and
we use getData() to specify the data type. We create a new jQuery element with
that and then use insertAfter() to place it after the current element. Remember,
each card is both draggable and a drop target.
The getData() method is available only in the drop() event. For security reasons,
the specification doesn’t allow any of the other drag-and-drop events to get
access to the stored data. The drop() event is the only time the browser can be
sure that the user didn’t cancel the event.
report erratum • discuss
Getting It All Sorted Out with Drag and Drop • 235
Download from Wow! eBook <www.wowebook.com>