views:

269

answers:

3

I've attached a focus listener to window (using prototype syntax):

Event.observe( window, 'focus', focusCb.bindAsEventListener( this ) );

I want to determine the mouse position when the window is focused. Unfortunately, in my focusCb method, I don't seem to have access to pageX, pageY, clientX or clientY.

Using quirksmode code:

function doSomething(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
    // Do something with this information
}

I always get 0, 0.

I thought the focus event would have the mouse position information.

  1. Why doesn't the focus event have this information?
  2. More importantly, how should get I get the mouse position when the window is focused?
+1  A: 

IE has clientX and clientY in the event object; though it may be the only one.

Yeah, this is looking pretty horrible. See the section on this page about Mouse Position. I think he does a pretty thorough job of examining it.

Okay, I see you're actually already using his script. Sigh.

jeffamaphone
Thank you; i clarified the question to include the quirksmode code I am using to get mouseposition in different browsers.
jedierikb
Yeah, at this point I'm just searching like you. See the link I just posted.
jeffamaphone
A: 

You can capture the window onclick event and throw the position into a globally scoped variable.

EDIT: Also if you're using prototype you should have access to the pointerX and pointerY methods of the event object.

Myles
That could work, but not if I tab back into the window.
jedierikb
Well in that case you might watch the onmousemove event then.
Myles
A: 

Depending on the circumstances, it might not exactly be what you're looking for, but you could, after the focus, wait for the next mousemove event and use that coordinates, something along this line:

var x = 0, y = 0, window_got_focus = false;
window.onfocus = function () { window_got_focus = true };
document.onmousemove = function (event) {
  if (window_got_focus) {
    window_got_focus = false;
    x = event.clientX;
    y = event.clentY;
  }
};

Drawback is, of course, that you get the coordinates only as soon as the user moves the mouse after focussing.

Boldewyn