Handling events with the DOM - Part III - The x-y game: determining mouse coordinates
(Page 6 of 7 )
The process of finding mouse position is rather messy and unreliable, because there are six mouse coordinate properties pairs, but they are not really available cross-browser. Due to this fact, most of them are useless for implemented in reliable mouse position detection scripts. The list of properties is shown below:
clientX, clientY
layerX, layerY
offsetX, offsetY
pageX, pageY
screenX, screenY
x, y
From the above listed properties, the only ones present in most browsers are "screenX" and "screenY". They give the mouse position relative to the entire computer screen of the user. However, this information is rather useless for implementing within a script, since most of the time we need to know mouse coordinates relative to the document, not the screen itself. So, I’d settle for just using the pairs "clientX, clientY" and "pageX, pageY" to determine mouse position in a cross browser manner. The JavaScript functionthat takes care of that might be coded as follows:
function detectMouseCoordinates(e){
var posx,posy;
posx=0;
posy=0;
if(!e) var e=window.event;
if(e.pageX||e.pageY){
posx=e.pageX;
posy=e.pageY;
}
else if(e.clientX||e.clientY){
posx = e.clientX + document.documentElement.scrollLeft;
posy = e.clientY + document.documentElement.scrollTop;
}
alert('X='+posx+' Y='+posy);
}
Once we’ve listed the function, we would call it this way:
document.onmousedown=detectMouseCoordinates;
Please note that in the case of Mozilla and Netscape, the function will be executed whether we’re left or right clicking on the document. If we’re dealing with IE, which supports the "clientX, clientY" properties, we calculate mouse position by first obtaining the coordinates relative to the client area of the browser and then adding the "scrollLeft" and "scrollTop" values, relative to the document element.
As you can appreciate, mouse coordinate detection is quite difficult to do accurately, due to annoying browser inconsistencies.
Our next section deals with mouse button detection. Let’s find out how it can be implemented in our JavaScript functions.
Next: Buttons from the bottom: detecting mouse buttons >>
More JavaScript Articles
More By Alejandro Gervasio