Java Reference
In-Depth Information
height: 200px;
}
.navy {
background-color: navy;
}
.red {
background-color: red;
}
Each draggable element uses the
box
class to set its height and width. The
navy
and
red
classes are used
in conjunction with the
box
class to give the element a background color of navy or red, respectively.
As for the JavaScript, you first retrieve two groups of elements—those that are draggable and those that
are drop targets:
var draggable = document.querySelectorAll("[draggable]");
var targets = document.querySelectorAll("[data-drop-target]");
So using the
document.querySelectorAll()
method, you retrieve both groups of elements with their
respective
[draggable]
and
[data‐drop‐target]
CSS selectors and assign them to the
draggable
and
targets
variables.
Next, you want to register the
dragstart
event listeners on the
draggable
elements:
for (var i = 0; i < draggable.length; i++) {
draggable[i].addEventListener("dragstart", handleDragStart);
}
Using a
for
loop, you iterate over the
draggable
collection and call the
addEventListener()
method
on each draggable object, passing
dragstart
as the event and the
handleDragStart()
function object
as the handler.
You then want to use a similar process on the target elements:
for (i = 0; i < targets.length; i++) {
targets[i].addEventListener("dragover", handleOverDrop);
targets[i].addEventListener("drop", handleOverDrop);
targets[i].addEventListener("dragenter", handleDragEnterLeave);
targets[i].addEventListener("dragleave", handleDragEnterLeave);
}
By using another
for
loop, you loop through the
targets
collection and register event handlers
for the
dragover
,
drop
,
dragenter
, and
dragleave
events. Two functions are used to handle
these four events: the
handleOverDrop()
function handles the
dragover
and
drop
events, and
handleDragEnterLeave()
handles
dragenter
and
dragleave
.
The first function,
handleDragStart()
, contains just a single line of code:
function handleDragStart(e) {
e.dataTransfer.setData("text", this.id);
}