HTML and CSS Reference
In-Depth Information
For the rest of this chapter I will be using Firefox to test the application. Chrome also supports DnD
but has a bug that won't allow you to access the dataTransfer object except in the drag event (see this article for
details - ) . opera will also work fine but IE9 doesn't support
DnD at all.
Allowing a Drop
You have draggable elements and all you need to complete a drag and drop operation is an element that will
accept a drop. To do that you'll need an event handler for the dragover event that sets the drop effect. By default
the effectAllowed property is set to all so setting the drop effect to move, copy, or link will all be valid settings. To
try this out, add a script element at the end of the body element and add the code shown in Listing 14-4.
Listing 14-4. The initial event implementation
<script type="text/javascript">
// Get all the black squares
var squares = document.querySelectorAll('.bblack');
var i = 0;
while (i < squares.length) {
var s = squares[i++];
// Add the event listeners
s.addEventListener('dragover', dragOver, false);
// Handle the dragover event
function dragOver(e) {
if (e.preventDefault) {
e.dataTransfer.dropEffect = "move";
This code uses the querySelectorAll() function that I described in Chapter 5 to get all of the black squares.
It then iterates through the collection that is returned and adds an event handler for the dragover event. The
dragover() function calls the preventDefault() function to cancel the browser's default action. It then gets the
dataTransfer object and sets the dropEffect property to “move”.
Press F5 to run the application and try dragging a checker. You should now get a move cursor on all the black
squares but a not allowed cursor on the white squares. Try dropping the checker on an empty black square. Since
you have not yet implemented a drop event handler the browser will execute its default drop action. Since the
item being dragged is an image, the default action is to navigate to the image file.
Performing the Custom Drop Action
The default action is not what we're looking for here so we'll need to implement the drop event hander and
provide our own logic. The drop event handler is where all the real work happens. This is where the file is deleted
if it's a trash can. For this application, the drop action will create a new img element at the target location and
remove the previous image.
Search WWH ::

Custom Search