Main Page

handleMouseDown

function handleMouseDown() {
EventUtil.addEventHandler(document.body, “mousemove”,
handleMouseMove);
EventUtil.addEventHandler(document.body, “mouseup”,
handleMouseUp);
}
function handleMouseUp() {
EventUtil.removeEventHandler(document.body, “mousemove”,
handleMouseMove);
EventUtil.removeEventHandler(document.body, “mouseup”,
handleMouseUp);
}
</script>
<style type=”text/css”>
#div1 {
background-color: red;
height: 100px;
width: 100px;
position: absolute;
}
</style>
</head>
<body>
<p>Try dragging the red square.</p>
<p><div id=”div1” onmousedown=”handleMouseDown()”></div> </p>
</body>
</html>
As you can see,
handleMouseDown()
simply adds the
onmousemove
and
onmouseup
event handlers
whereas
handleMouseUp()
removes the event handlers. Doing this prevents the dragging functionality
from working by mistake. In this example, the only thing that can initiate the drag is the user holding
the mouse button down on the
<div/>
.
When you try this out, note that the upper-left corner of the
<div/>
always lines up with the cursor,
which is okay, but it’s a little jarring to users. Ideally, the
<div/>
should look like it was
picked up
by the
cursor, meaning that the point where the user clicked should be where the cursor appears to remain,
even though the
<div/>
is moving (see Figure 13-1).
Figure 13-1
User initially clicks here
When being dragged,
the cursor ends up here
401
Drag and Drop
16_579088 ch13.qxd 3/28/05 11:41 AM Page 401


JavaScript EditorFree JavaScript Editor     Ajax Editor


©