Click to See Complete Forum and Search --> : Teeny Tiny Problem


DJRobThaMan
07-31-2003, 11:53 AM
I'm trying to make a draggable div using javascript and I'm having a bit of a problem to clear document.onmousemove after I've already applied the function I'm using to follow the cursor with the div.


Anybody have any ideas as to how I could do this?

Here's what I'm using:


<html>
<head>
<script type="text/JavaScript">
<!--
var i;
var j;

function trackit(){
i = event.x;
j = event.y;
document.getElementById("tracker").style.left = i;
document.getElementById("tracker").style.top = j;
}
function drag(){
document.onmousemove = trackit;
}
function enddrag(){
???????????????????????
}
-->
</script>
</head>
<body>
<div id="tracker" style="position:absolute;background-color:red;width:50;height:50;" onMouseDown="drag()" onMouseUp="enddrag()">
</div>
</body>
</html>



Thanks

Exuro
07-31-2003, 06:36 PM
Here's the code with the parts I edited in bold:

<html>
<head>
<script type="text/JavaScript">
<!--
var i;
var j;

function trackit(){
i = event.x-10;
j = event.y-10;
document.getElementById("tracker").style.left = i;
document.getElementById("tracker").style.top = j;
}
function drag(){
document.onmousemove = trackit;
}
function enddrag(){
document.onmousemove=null;
}
-->
</script>
</head>
<body>
<div id="tracker" style="position:absolute;background-color:red;width:50;height:50;" onMouseDown="drag();" onMouseUp="enddrag();">
</div>
</body>
</html>

First thing I did was add in the "-10"s to the position of the division. You need this because otherwise the cursor is no longer over the division when it's being moved. If the cursor is not over the division, then the onMouseUp isn't going to be called. The other thing I did was have the document.onmousemove set to null when function enddrag() is called. All that does is tells the document to do nothing when the mouse moves. Hope that works for you!