15.02.2013 Views

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

104<br />

<strong>JavaScript</strong> <strong>Examples</strong> <strong>Bible</strong>: The Essential Companion to <strong>JavaScript</strong> <strong>Bible</strong><br />

elementObject.onDrag<br />

atop a drop target, the cursor is the “copy” style. Figure 1-4 shows the cursor effect<br />

as the user drags a selected word from the columns to a blank field that is scripted as<br />

a drop target. Finally, the setupDrag() function is the first to execute in the drag<br />

operation, so a timer is set to the current clock time to time the drag operation.<br />

Figure 1-4: The cursor turns to a “copy” icon atop a designated drop target<br />

The onDrag event handler (in the BODY) captures the onDrag events that are<br />

generated by whichever table cell element is the source element for the action.<br />

Each time the event fires (which is a lot during the action), the timeIt() function<br />

is invoked to compare the current time against the reference time (global timer)<br />

set when the drag starts. If the time exceeds two seconds (2,000 milliseconds), an<br />

alert dialog box notifies the user. To close the alert dialog box, the user must<br />

unclick the mouse button to end the drag operation.<br />

To turn the blank SPAN elements into drop targets, their onDragEnter,<br />

onDragOver, and onDrop event handlers must set event.returnValue to false;<br />

also, the event.dataTransfer.dropEffect property should be set to the desired<br />

effect (copy in this case). These event handlers are placed in the P element that<br />

contains the two SPAN elements, again for simplicity. Notice, however, that the<br />

cancelDefault() functions do their work only if the target element is one of the<br />

SPAN elements whose ID begins with “blank.”<br />

As the user releases the mouse button, the onDrop event handler invokes the<br />

handleDrop() function. This function retrieves the string data from event.<br />

dataTransfer and restores it to an array data type (using the String.split()<br />

method). A little bit of testing makes sure that the word type (“noun” or “adjective”)<br />

is associated with the desired blank. If so, the source element’s text is set to<br />

the drop target’s innerText property; otherwise, an error message is assembled to<br />

help the user know what went wrong.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!