Reputation: 409
Here's my simple code.It contains division, which moves on dragging with mouse (on x axis) anywhere on screen.Everything works perfect on first drag, but on second division comes back to it's original position, which is centre of screen.I know why does this happen, but can't figure out how to fix it.My point is to continue moving division from coords where previous drags moved it.
<!DOCTYPE html>
<html>
<head>
</head>
<body style="overflow:hidden">
<style>
#screen
{
width:200px;
height:300px;
position:absolute;
top:0;bottom:0;left:0;right:0;
margin:auto;
border-style:solid;
}
</style>
<script>
var exit=0;
document.onmousedown=function(e)
{
exit=1;
x=e.pageX;
document.onmousemove= function(e)
{
if(exit==1)
{
y=e.pageX;
final=x-y;
document.getElementById("screen").innerHTML=final;
document.getElementById("screen").style.left=final+"px";
}
};
};
document.onmouseup=function(e)
{
exit=0;
}
</script>
<div id="screen">
</body>
</html>
Upvotes: 0
Views: 103
Reputation: 316
You want to store the "final" value so that you can use it as an offset on the next click. What's happening is that you are using the mouse down and mousemove X difference to move the object, but on second click you are not taking into consideration that the object was offseted by the previous "final" value and it has to be moved with that offset in mind! Here's the code snippet working, and the jsfiddle link below:
var exit=0;
var final = 0;
document.onmousedown=function(e)
{
exit=1;
x=e.pageX + final;
document.onmousemove= function(e)
{
if(exit==1)
{
y=e.pageX;
final=x-y;
document.getElementById("screen").innerHTML=final;
document.getElementById("screen").style.left=final+"px";
}
};
};
document.onmouseup=function(e)
{
exit=0;
}
jsfiddle:
http://jsfiddle.net/dcasadevall/NELWW/
Upvotes: 1