HTML and CSS Reference
In-Depth Information
3.
Handle drag-and-drop related events.
4.
If required, transfer data between the drag source and the drop target.
Enable Dragging for HTML Elements
The first step in using drag-and-drop in a page is to make one or more elements draggable. You do this by
setting the draggable attribute of an HTML element to true . For example, the following piece of markup
makes a <div> element draggable:
<div class="myclass" draggable="true">Some content</div>
Drag-and-Drop Events
Marking one or more DOM elements as draggable is just a part of the story. To actually make your drag-
and-drop functional and visually appealing to the end user, you need to handle certain events. These
events are listed in Table 9-7.
Table 9-7. Drag-and-Drop Events
Event
Description
dragstart
Raised when the drag operation begins
drag
Raised when an element is dragged
dragenter
Raised when a draggable element is dragged and enters a valid drop
target
dragleave
Raised when a draggable element that was dragged on a valid drop target
leaves the drop target
dragover
Raised when a draggable element is being dragged over a valid drop
target
drop
Raised when a dragged element is dropped onto a valid drop target
dragend
Raised when the drag operation ends
Note that a drag source is an element that is being dragged, whereas a drop target is an element on
which a draggable element is to be dropped. Events from Table 9-7 such as dragstart , drag , and dragend
are handled by a drag source, whereas events such as dragenter , dragleave , dragover , and drop are
handled by a drop target. You can wire event handlers to these events using JavaScript, as shown in Listing
9-6.
Listing 9-6. Wiring Event Handlers for Drag-and-Drop Events
$("div").each(function () {
this.addEventListener('dragstart', OnDragStart, false);
this.addEventListener('drop', OnDrop, false);
});
In this code, the dragstart and drop events of <div> elements are wired to OnDragStart and OnDrop
functions respectively using addEventListener() method.
 
Search WWH ::




Custom Search