Main Page

Drag and Drop

position: absolute;
left: 300px;
}
</style>
</head>
<body onload=”doLoad()”>
<p>Try dragging the red square onto the blue square.</p>
<div id=”div1”></div>
<div id=”divDropTarget”></div>
</body>
</html>
As you can see, the JavaScript section of this code is markedly smaller than that of the example in the
previous section. The first two lines of JavaScript create the
zDraggable
and
zDropTarget
objects.
Then, the drop target is registered to the
zDraggable
object by using
addDropTarget()
. Finally, an
event handler for the
drop
event is added to the drop target. That event handler moves the draggable
element to the upper-left corner of the drop target by making use of the previously mentioned methods.
Remember, the
relatedTarget
property of the
event
object is equal to the draggable element when
used in a
drop
event.
Of course, all this code must be called after the page has been loaded, so the
onload
event handler is
used for that purpose.
Summary
This chapter introduced the concept of drag and drop in a Web browser and explained the difference
between system drag and drop and simulated drag and drop.
You learned about Internet Explorer’s built-in system drag-and-drop functionality, and that it is the only
browser that supports system drag and drop from Web pages. The various events and methods pro-
vided by IE to work with system drag and drop were also discussed, as well as strategies for dragging
text and links.
Next you learned about simulated drag and drop, a way to use the DOM to move elements around that
gives the appearance of drag-and-drop functionality. You were shown how to build a simple drag-and-
drop example.
Lastly, you were introduced to the zDragDrop library, a free JavaScript library that encapsulates a great
deal of simulated drag-and-drop functionality. Using this library, you learned how to create a drag-and-
drop example making use of the custom objects, methods, and events.
409
Drag and Drop
16_579088 ch13.qxd 3/28/05 11:41 AM Page 409


JavaScript EditorFree JavaScript Editor     Ajax Editor


©