Main Page

Creating drop targets

function handleMouseUp() {
EventUtil.removeEventHandler(document.body, “mousemove”, handleMouseMove);
EventUtil.removeEventHandler(document.body, “mouseup”, handleMouseUp);
Making these changes allows the
to be dragged in a nicer-looking way.
Creating drop targets
Now that you know how to drag an element around the screen, all you need is a place to drop it.
Creating a drop target for simulated drag and drop involves checking the coordinates of the mouse to
see if it is located inside the boundaries of the drop target.
Like the dragged item, the drop target is also absolutely positioned so you can use the element’s
, and
properties to determine the x and y coordi-
nates of each corner. The function
is designed to encapsulate this evaluation by
taking a set of coordinates as arguments and returning
if the coordinates are within the drop target.
function isOverDropTarget(iX, iY) {
var oTarget = document.getElementById(“divDropTarget”);
var iX1 = oTarget.offsetLeft;
var iX2 = iX1 + oTarget.offsetWidth;
var iY1 = oTarget.offsetTop;
var iY2 = iY1 + oTarget.offsetHeight;
return (iX >= iX1 && iX <= iX2 && iY >= iY1 && iY <= iY2);
The first line in the function gets a reference to the element with the ID of
. The fol-
lowing lines determine the two x coordinates and two y coordinates. The last line tests to see if the coor-
dinate arguments are located within the drop target, returning
if so or
if not.
function handleMouseUp() {
var oEvent = EventUtil.getEvent();
EventUtil.removeEventHandler(document.body, “mousemove”, handleMouseMove);
EventUtil.removeEventHandler(document.body, “mouseup”, handleMouseUp);
if (isOverDropTarget(oEvent.clientX,oEvent.clientY)) {
var oDiv = document.getElementById(“divDropTarget”);
var oTarget = document.getElementById(“div2”); = oTarget.offsetLeft; = oTarget.offsetTop;
The highlighted section of code shows an alert if the cursor is over the designated drop target. Then, the
dragged element is positioned into the upper-left corner of the drop target so it appears to
place. Of course, if you have more than one item to drag onto a drop target, you must create some sort
Drag and Drop
16_579088 ch13.qxd 3/28/05 11:41 AM Page 403

JavaScript EditorFree JavaScript Editor     Ajax Editor