Main Page

Creating drop targets

function handleMouseUp() {
EventUtil.removeEventHandler(document.body, “mousemove”, handleMouseMove);
EventUtil.removeEventHandler(document.body, “mouseup”, handleMouseUp);
}
Making these changes allows the
<div/>
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
offsetLeft
,
offsetTop
,
offsetHeight
, and
offsetWidth
properties to determine the x and y coordi-
nates of each corner. The function
isOverDropTarget()
is designed to encapsulate this evaluation by
taking a set of coordinates as arguments and returning
true
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
“divDropTarget”
. 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
true
if so or
false
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)) {
alert(“dropped!”);
var oDiv = document.getElementById(“divDropTarget”);
var oTarget = document.getElementById(“div2”);
oDiv.style.left = oTarget.offsetLeft;
oDiv.style.top = 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
snap
into
place. Of course, if you have more than one item to drag onto a drop target, you must create some sort
403
Drag and Drop
16_579088 ch13.qxd 3/28/05 11:41 AM Page 403


JavaScript EditorFree JavaScript Editor     Ajax Editor


©