↑
Main Page
The code
function handleMouseMove(oEvent) {
var oDiv = document.getElementById(“div1”);
oDiv.style.left = oEvent.clientX;
oDiv.style.top = oEvent.clientY;
}
</script>
<style type=”text/css”>
#div1 {
background-color: red;
height: 100px;
width: 100px;
position: absolute;
}
</style>
</head>
<body onmousemove=”handleMouseMove(event)”>
<p>Try moving your mouse around.</p>
<p><div id=”div1”></div> </p>
</body>
</html>
In this example, a red
<div/>
follows the cursor around. Every time the cursor moves, the
<div/>
is
positioned at the same position, making its upper-left corner equal to the point of the cursor. Note that
the
onmousemove
event handler is assigned for the
<body/>
element, not for the
<div/>
. This is
because you must track the mouse movement over the entire page, not just within the
<div/>
.
To simulate drag and drop, the
<div/>
shouldn’t just move around on its own; the drag must be initi-
ated and stopped. This is where the code gets a little bit tricky and requires the use of the
EventUtil
object from earlier in the book.
The code
The first step is to create three functions: one to handle each of three mouse events (
mousemove
,
mouse-
down
, and
mouseup)
. The function that handles
mousedown
is assigned to the
<div/>
(or the element to be
dragged). When the user ’s mouse button is pushed down over the
<div/>
, this function assigns the event
handlers for
mousemove
and
mouseup
on
document.body
. When the user releases the mouse button, the
dragging stops and the event handlers for
mousemove
and
mouseup
are removed. Here’s the code:
<html>
<head>
<title>Simulated Drag And Drop Example</title>
<script type=”text/javascript” src=”eventutil.js”></script>
<script type=”text/javascript”>
function handleMouseMove() {
var oEvent = EventUtil.getEvent();
var oDiv = document.getElementById(“div1”);
oDiv.style.left = oEvent.clientX;
oDiv.style.top = oEvent.clientY;
}
400
Chapter 13
16_579088 ch13.qxd 3/28/05 11:41 AM Page 400
Free JavaScript Editor
Ajax Editor
©
→