Java Reference
In-Depth Information
The
dragenter
event looks important; after all, it lets you know when the mouse cursor enters the
drop zone while dragging an object. But in actuality, it's optional. You cannot complete a drag‐and‐
drop operation with the
dragenter
event. Instead, you have to listen for the drop zone's
dragover
event.
This is where things start to get weird. For the
drop
event to fire, you have to prevent the behavior
of the
dragover
event. So, you basically have to call
preventDefault()
on the
Event
object every
time you listen for the
dragover
event.
Dropping Objects on a target
trY it out
In this Try It Out, you write a simple example that lets you drag and drop an element onto a target.
Open your text editor and type the following:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 10: Example 19</title>
<style>
.box {
width: 100px;
height: 100px;
}
.red {
background-color: red;
}
.drop-zone {
width: 300px;
padding: 20px;
border: 2px dashed #000;
}
</style>
</head>
<body>
<div draggable="true" class="box red"></div>
<div id="dropZone" class="drop-zone">Drop Zone!</div>
<div id="dropStatus"></div>
<script>
function dragDropHandler(e) {
e.preventDefault();
if (e.type == "dragover") {
dropStatus.innerHTML = "You're dragging over the drop zone!";
} else {
dropStatus.innerHTML = "You dropped something!";
}
}
var dropZone = document.getElementById("dropZone");