Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Roy Marchand http://www.expertsrt.com

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Detecting Mouse Position

This is an easy way to determine the mouse position (click anywhere and the co-ordinates get displayed:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<head>
   <title>Mouse co-ordinates</title>
   <style type="text/CSS">
      .holder {background-color:lightyellow;color:blue;width:40}
   </style>
<script type="text/javascript">
function showit()
{
   document.forms['theform'].xcoord.value=event.x;
   document.getElementById('spanx').innerHTML='x='+event.x;
   document.forms.theform.ycoord.value=event.y;
   document.getElementById('spany').innerHTML='y='+event.y;
}
function showitMOZ(e)
{
   document.forms['theform'].xcoord.value=e.pageX;
   document.getElementById('spanx').innerHTML='x='+e.pageX;
   document.getElementById('spany').innerHTML='y='+e.pageY;
   document.forms.theform.ycoord.value=e.pageY;
}
if (!document.all){
window.captureEvents(Event.CLICK);
window.onclick=showitMOZ;
}
else
{
document.onclick=showit;
}
</script>
</head>
<body>
<br><br><br>
<h1>You can store them in form fields</h1>
<form name="theform">
x = <input name="xcoord" style="width:40"> 
y = <input name="ycoord" style="width:40">
</form>
<br /><br />
<h1> or as plain text</h1>
<span id="spanx">&nbsp;</span>
<span id="spany">&nbsp;</span>
</body>
</html>



Of course knowing the co-ordinates also makes it possible to position elements based on the position of the mouse pointer. It will work for any mouse event Mouseover, mouseout, etc; just change click to the desired event in the final if statement of the script. More good stuff and articles at the home of real IT Mentors
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS