AJAX - The Complete Reference

(avery) #1

368 Part II: Developing an Ajax Library^


Once the events are bound, the user can invoke dragging by holding the mouse button
down while on top of a draggable object. This action will invoke the function
dragDropStart(), passing in the event object and a reference to the drug object. In this
function, first, browser inconsistencies in handling the Event object are addressed. Then
the position of the object is calculated. Finally, the handlers that are used to handle the
dragging and the release of the button which stops the process are bound.

function dragDropStart(e, obj)
{
/* first we address browser differences for finding the event object */
e = fixE(e);
/* next we calculate the offset of the difference between top/left and
the position, note we have called our own getStyle() and getPosition()
functions to address cross browser differences for finding these values */
var position = getPosition(e);
var left = parseInt(getStyle(obj, "left"), 10);
var top = parseInt(getStyle(obj, "top"), 10);

/* if problems with the position reset it to zero values */
if (isNaN(left))
left = 0;
if (isNaN(top))
top = 0;
var xOffset = left - position.x;
var yOffset = top - position.y;
/* set z-index to be the largest on the page so that it drags on top of
everything */
obj.style.zIndex = (getHighestZIndex() + 1);

/* set up the movement handler */
document.onmousemove = function(e){return dragDropMove(e, obj, xOffset,
yOffset);};
/* define the handler to stop dragging upon mouse release */
document.onmouseup = function(e){dragDropStop();};
/* kill any event propagation and default actions */
e.cancelBubble = true;
e.returnValue = false;
if (e.stopPropagation)
{
e.stopPropagation();
e.preventDefault();
}
}

Readers may want to note a few other aspects of the preceding code above. First, note
the decision we made in the example to set the objects to the highest z-index in order to
make the dragging allow reshuffling of stacking. Also, notice the handling of event
propagation and bubbling, as we do not want the dragging and movement events to trigger
other activities accidentally. If you are bothered by the amount of code necessary to deal
with differences in event handling in browsers you aren’t alone. Fortunately, many of the
Free download pdf