Java Reference
In-Depth Information
The box class sets the element's width and height properties to 100 pixels, and red gives the element a
background color of red. These are arbitrary values meant to only give the draggable element some visibility.
Next, the HTML. The only new element in this HTML document is a draggable <div/> element:
<div draggable="true" class="box red"></div>
To make it draggable, you set the draggable attribute to true , and you apply the box and red CSS
classes to make it easier to drag and drop.
But as with Example 18, the good stuff is in the JavaScript. First, you register listeners for the
dropZone 's dragover and drop events:
dropZone.addEventListener("dragover", dragDropHandler);
dropZone.addEventListener("drop", dragDropHandler);
Let's look at the dragDropHandler() function. The very first line calls the Event object's
preventDefault() method:
function dragDropHandler(e) {
e.preventDefault();
This is crucial for two reasons. First, the dragover is default behavior must be prevented in order for
the drop event to fire (and that's kind of important).
Second, the browser will do something when you drop an object. In other words, the drop event has a default
behavior, but the exact behavior depends on the browser and the object that you drop. Some examples are:
For a file or image, most browsers will attempt to open it.
Dropping a URL may cause the browser to navigate to the URL.
In Firefox, dropping an element will cause the browser to navigate to the value in the element's id
attribute.
Therefore, you want to prevent the drop event's default behavior in most cases.
After preventing the default behavior, the dragDropHandler() function changes the content of the
dropStatus element based on the type of event:
if (e.type == "dragover") {
dropStatus.innerHTML = "You're dragging over the drop zone!";
} else {
dropStatus.innerHTML = "You dropped something!";
}
}
For the dragover event, it simply states that you are dragging over the target element; otherwise, the
function knows that you dropped something and tells you so.
Frustratingly, native drag and drop doesn't work exactly the same in all modern browsers. The
aforementioned partial list of the browsers' default behavior for the drop event is just one thing
JavaScript developers have to contend with.
 
Search WWH ::




Custom Search