Friday, February 27, 2009

Javascript mouse position capture

Capturing mouse position on the screen is often needed in creating modern web pages, with better functionality. Here's a small script that captures the mouse position on every mouse move and stores it in a couple of global variables that can be used from anywhere within the page.
//Add an event listener for mouse move, depending on client browser. 
if(document.layers) 
{ 
 document.captureEvents(Event.MOUSEMOVE);
 document.onmousemove = captureMousePosition;
} 
else if(document.all) 
 document.onmousemove = captureMousePosition;
else if(document.getElementById)  
 document.onmousemove = captureMousePosition;

//Declare the variables that will store the coordinates
var xMousePos = 0; //abscissa
var yMousePos = 0; //ordinate

//Capture the position, again depending on client's browser
function captureMousePosition(e) 
{
 if(document.layers) 
 {
  xMousePos = e.pageX;
      yMousePos = e.pageY;
   } 
   else if(document.all) 
   {
  xMousePos = window.event.x+document.body.scrollLeft;
      yMousePos = window.event.y+document.body.scrollTop;
   } 
   else if(document.getElementById) 
   {
  xMousePos = e.pageX;
      yMousePos = e.pageY;
   }
}
This simple script allows us to know where the mouse is and do a lot of stuff according to it, most commonly - move elements around or knowing exactly where the user has clicked. I use this script oftenly and it will mantioned quite often from now on. Actually, I've already used it in some of the old scripts, but decided to separate it and make it available for you on http://enikoloff.info/scripts/mousePos.js You can see an example page here.

2 comments:

Armitage said...

I've tried to do this on a page centered in the window, and the math seems to be off in that circumstance. It seems that position is to the right about 1 half the difference between the page width and the width of the window. Any pointers on how I can avoid that?

Nikoloff said...

This script calculates the position based on the body width and height. I can't say for sure what is the problem, without seeing your page, but I bet it has something to do with the way that you center the elements on the page. Post more information here (or just a link to the page) and I'll try to help :)