HTML and CSS Reference
In-Depth Information
In the dragstart event handler you can specify the drop effects that are allowed based on the source
element that is selected. You can specify more than one allowed effect by simply concatenating them (for
example “copyMove”) or specify all effects like this:
e.dataTransfer.effectAllowed = "all"; // "copy", "link", "move", "copyLink", "linkMove",
"copyMove"
Then, in the dragover event, you'll specify the drop effect that will occur if the source element is dropped
there. If that drop effect is one of the allowed effects, the cursor will change to indicate that drop effect. If that
effect is not allowed, however, the cursor will use the “not allowed” icon. If this is not a valid location to accept
the drop, set the drop effect to “none” like this:
if (validLocation) {
e.dataTransfer.dropEffect = "move";
}
else {
e.dataTransfer.dropEffect = "none";
}
Enabling Draggable Elements
So now you know you can disable the drop event on an element by setting the drop effect to “none” in the
dragover event. But how do you control which elements can be dragged to start with? The answer is simple: just
set the draggable attribute in the markup for the element. For example, to create a div that can be dragged, enter
the markup like this:
<div id="myDiv" draggable="true">
<p>This div is draggable</p>
</div>
By default, images and links are draggable. Go to the google.com and try dragging the Google logo. You
should see a somewhat muted copy of this image being dragged as you move the cursor.
If you drag this image onto a Firefox browser window, Firefox will navigate to this image. You've just
seen drag and drop in action. Because using drag and drop is such a natural way of working, browsers try to
accommodate this out-of-the-box as best they can. For example, if you drag some text from a text editor that
appears to be a URL onto a browser, it will try to navigate to that address. If you drag an image file onto a browser
it will either navigate to it or download it.
Sometimes the default action can cause issues with your custom code. I will show you later in the chapter
how to disable this.
Not For more information on the DnD API, check out the W3C specification at
http://dev.w3.org/html5/spec/single-page.html#dnd .
Creating the Checkers Application
To demonstrate the DnD API, you'll create a web application that displays a typical checkers board of alternating
red and white squares. You'll use image files to represent the checkers and display them in their initial starting
position. Then you'll create event handlers that will allow you to move a piece to a different square. Finally, you'll
add logic to disable illegal moves.
 
 
Search WWH ::




Custom Search