HTML and CSS Reference
In-Depth Information
The crucial event in the drag-and-drop process is
dragOver
. Any ele-
ment that is to be a target for dropped elements must capture the
dragOver
event and cancel the default action on it:
function dragOver(event) {
event.preventDefault();
log('dragOver ' + event.target.id);
}
When the element is dropped, the
drop
event is fired. It's in this event
that the actual work needs to be done. This example removes the list
item from the source list and adds it to the selected list using the stan-
dard
appendChild
method:
function drop(event) {
var id = event.dataTransfer.getData('Text');
event.target.appendChild(document.getElementById(id));
log('drop ' + event.target.id);
event.preventDefault();
}
These two events can be bound declara-
tively to the
drop
target element:
ondragover="dragOver(event)"
</ul>
<ul id="drophere"
ondrop="drop(event)">
As you can see, the
dragOver
event is
fired repeatedly while the dragged ele-
ment is over the
drop
target.
If you only want drag-and-drop to work in Firefox, Chrome, and
Safari, that's all the code you need—you're done! If you want it to
work in
IE
too, read ahead to the next section.