Main Page

Some calculations

Some calculations can be done to make the cursor appear in the proper position. To do this, you capture
the difference between where the
<div/>
is located and where the cursor is located when it is initially
clicked (in the
handleMouseDown()
function). You compare the
clientX
and
clientY
properties of the
event object to the
offsetLeft
and
offsetTop
properties of the
<div/>
(see Figure 13-2).
Figure 13-2
The differences between the x and y coordinates must be stored outside of the functions so that each
function can have access to the values. The variables to store these differences are called
iDiffX
and
iDiffY
, and they are initialized in the
handleMouseDown()
function before the event handlers are
added to
document.body
. Then, in
handleMouseMove()
, these values are subtracted from
clientX
and
clientY
, respectively, to move the
<div/>
into the correct position:
var iDiffX = 0;
var iDiffY = 0;
function handleMouseMove() {
var oEvent = EventUtil.getEvent();
var oDiv = document.getElementById(“div1”);
oDiv.style.left = oEvent.clientX - iDiffX;
oDiv.style.top = oEvent.clientY - iDiffY;
}
function handleMouseDown() {
var oEvent = EventUtil.getEvent();
var oDiv = document.getElementById(“div1”);
iDiffX = oEvent.clientX - oDiv.offsetLeft;
iDiffY = oEvent.clientY - oDiv.offsetTop;
EventUtil.addEventHandler(document.body, “mousemove”, handleMouseMove);
EventUtil.addEventHandler(document.body, “mouseup”, handleMouseUp);
}
402
Chapter 13
16_579088 ch13.qxd 3/28/05 11:41 AM Page 402


JavaScript EditorFree JavaScript Editor     Ajax Editor


©