Java Reference
In-Depth Information
Its purpose is simple: to store the
id
of the draggable element. Notice the use of
this
in
this.id
. When
you register an event listener, the handler function executes within the context of the element object the
event fired on. In this case, the
dragstart
event fired on one of the draggable elements; so,
this
refers
to that element. In other words,
this
is the same as
e.target
.
The next function is
handleDragEnterLeave()
, and as mentioned earlier, it executes when the
dragenter
and
dragleave
events fire on a drop target:
function handleDragEnterLeave(e) {
if (e.type == "dragenter") {
this.className = "drag-enter";
} else {
this.className = "";
}
}
The first line of this function checks the type of event that occurred. If the event is
dragenter
, the
CSS class of the drop target element is set to
drag‐enter
(once again, notice
this
is used instead of
e.target
—it's much easier to type). If the event isn't
dragenter
, the element's CSS class is set to an
empty string, thus removing the
drag‐enter
class.
The final function,
handleOverDrop()
, performs the real magic of the drag‐and‐drop operation. This
function handles both the
dragover
and
drop
events and should therefore prevent the default action
from occurring. Thus, the first line of the function calls
e.preventDefault()
:
function handleOverDrop(e) {
e.preventDefault();
This is all that is needed for the
dragover
event. So, if the event isn't a
drop
event, the function simply exits:
if (e.type != "drop") {
return;
}
If it is a
drop
event, the function continues on and retrieves the draggable element's
id
from the
DataTransfer
object:
var draggedId = e.dataTransfer.getData("text");
var draggedEl = document.getElementById(draggedId);
And with this
id
, you retrieve the draggable element's object with
document.getElementById()
and
store it in the
draggedEl
variable.
You have two options when it comes to dropping one of the draggable boxes: you can either drop it
in the target it's currently in, or you can drop it in another target. If dropped in its current location,
there's nothing left to do except reset the target's CSS class. This is easy enough to check; simply use the
element's
parentNode
property:
if (draggedEl.parentNode == this) {
this.className = "";
return;
}