PDA

View Full Version : Detecting direction of mouse movement



dragon6158
05-14-2008, 02:10 PM
Hello,
Is there a way to detect the direction that the mouse is moved?

Thanks,
Don

Kor
05-14-2008, 04:14 PM
there is a way to detect the mouse coordinates. Now it's up to you what do you mean by "direction". Direction relative to what?


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
var posx;var posy;
function getMouse(e){
posx=0;posy=0;
var e=(!e)?window.event:e;//IE:Moz
if (e.pageX){//Moz
posx=e.pageX+window.pageXOffset;
posy=e.pageY+window.pageYOffset;
}
else if(e.clientX){//IE
if(document.documentElement){//IE 6+ strict mode
posx=e.clientX+document.documentElement.scrollLeft;
posy=e.clientY+document.documentElement.scrollTop;
}
else if(document.body){//Other IE
posx=e.clientX+document.body.scrollLeft;
posy=e.clientY+document.body.scrollTop;
}
}
else{return false}//old browsers
document.getElementById('myspan').firstChild.data='X='+posx+' Y='+posy;
}
document.onmousemove=getMouse
</script>
</head>
<body>
<span id="myspan">&nbsp;</span>
</body>
</html>

Stooshie
05-14-2008, 04:27 PM
there is a way to detect the mouse coordinates. Now it's up to you what do you mean by "direction". Direction relative to what?


Presumably relative to the last co-ordinates.

I'm working on a bit of code. will post shortly.

Stooshie
05-14-2008, 04:41 PM
Ok, try this


<html>
<head>
<script type="text/javascript">
var x;
var y;
var old_x;
var old_y;
// added below
var anglerad;
var anglerad;
// added above
function get_coords(event)
{
x=event.clientX;
y=event.clientY;
yd = (y - old_y);
xd = (x - old_x);
dxy = (yd/xd);
anglerad = Math.atan(dxy);
angledeg = (180/Math.PI) * anglerad;
document.getElementById("mytext").value = anglerad + " :: " + angledeg;
old_x = x;
old_y = y;

}
</script>
</head>

<body onmousemove="get_coords(event)">

<p>Move the mouse around</p>

<input type="text" id="mytext" style="width:30em;"/>

</body>
</html>


--- EDIT ---
I Have added two lines to the code so all you have to do at any point in the page is refer to anglerad or angledeg in your own code.