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.

118<br />

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

offsetX and offsetY variables (minus any scrolling that the body is subject to at<br />

that instant). These offset values are necessary to let the scripts set the location of<br />

the image during dragging (the location is set for the top-left corner of the image)<br />

while keeping the cursor in the same location within the image as when the user<br />

first presses the mouse.<br />

As the user drags the image, the onMouseDown event handler fires repeatedly,<br />

allowing the dragIt() function to continually update the location of the element<br />

relative to the current cursor position (the event.clientX and event.clientY<br />

properties). The global offset variables are subtracted from the cursor position to<br />

preserve the relation of the image’s top-left corner to the initial cursor position at<br />

mouse down.<br />

Upon the user releasing the mouse button, the release() function turns off the<br />

onMouseMove event handler (setting it to null). This prevents the event from being<br />

processed at all during normal usage of the page. The selectedObj global variable<br />

is also set to null, turning off the “switch” that indicates dragging is in session.<br />

Listing 15-43: Dragging Elements with onMouseMove<br />

<br />

onMouseMove Event Handler<br />

<br />

#camap {position:absolute; left:20; top:120}<br />

#ormap {position:absolute; left:80; top:120}<br />

#wamap {position:absolute; left:140; top:120}<br />

<br />

<br />

// global variables used while dragging<br />

var offsetX = 0<br />

var offsetY = 0<br />

var selectedObj<br />

var frontObj<br />

// set document-level event handlers<br />

document.onmousedown = engage<br />

document.onmouseup = release<br />

// positioning an object at a specific pixel coordinate<br />

function shiftTo(obj, x, y) {<br />

obj.style.pixelLeft = x<br />

obj.style.pixelTop = y<br />

}<br />

// setting the z-order of an object<br />

function bringToFront(obj) {<br />

if (frontObj) {<br />

frontObj.style.zIndex = 0<br />

}<br />

frontObj = obj<br />

frontObj.style.zIndex = 1<br />

}<br />

elementObject.onMouseMove

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

Saved successfully!

Ooh no, something went wrong!