Monday, April 2, 2012

The correct way to get mouse coordinates

I still saw some developers try to use different formular / ways to find out the mouse coordinates.  Well, according to the documentation, there is always only one correct cross-browser way to find out the real mouse coordinates   relative to the browser.   (  Note: mouse coordinates relative to your computer screen is not very useful for most of our cases, so the below is mouse coordinates relative to browser. )

Here is how the recommended implementation looks like :)
function myCallBack(e) {
 var posx = 0;
 var 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.body.scrollLeft
   + document.documentElement.scrollLeft;
  posy = e.clientY + document.body.scrollTop
   + document.documentElement.scrollTop;
 }
 // posx and posy contain the mouse position relative to the document
}

3 comments:

  1. posx - don't work.

    ReplyDelete
  2. This probably won't work in IE8, you need to use the global `event` there..

    ReplyDelete
  3. Works in Chrome for me, but not FF 24.0.

    ReplyDelete