AJAX - The Complete Reference

(avery) #1

PART II


Chapter 8: User Interface Design for Ajax 373


triggered, the dragDropStop() function would be modified to not only cancel the
dragging but also to compare the current position of the object being drug with any “drop
zones” in the page. Note the function call to within() in the following code to check this.

function dragDropStop(e)
{
/* detach event handlers */
document.onmousemove = null;
document.onmouseup = null;

e = fixE(e);
e.cancelBubble = true;
e.returnValue = false;
if (e.stopPropagation)
{
e.stopPropagation();
e.preventDefault();
}
/* get drop zones and determine if we ended up
in one and if so fire an action */
var cart = document.getElementById("cart");
var trashcan = document.getElementById("trashcan");
if (within(e, cart))
alert("Added to cart");
if (within(e, trashcan))
alert("Trashing the item");
}

In the function within(),the position we ended up at is compared with the position
of the container in question. Unfortunately, there is a bit of work done to calculate the
bounding box of the drop zone in a call to getOffsetPosition().

function within(e, container)
{
var position = getPosition(e);
var containerPosition = getOffsetPosition(container);
return (position.x >= containerPosition.x &&
position.x < (containerPosition.x + container.offsetWidth) &&
position.y >= containerPosition.y &&
position.y < (containerPosition.y + container.offsetHeight));
}

The complete code can be found at http://ajaxref.com/ch8/drop.html. A rendering of
the example is shown in Figure 8-10.

Draggable List


To show an application of drag-and-drop, we show the direct reordering of list items as we
might put in the to-do list example by dragging. Given simple markup defining the list:

<ol id="orderedList">
<li id="item1" class="draggable">Item #1</li>
Free download pdf