Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

determining mouse position on a window focus event

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?
like image 742
jedierikb Avatar asked Nov 08 '09 17:11

jedierikb


2 Answers

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.

like image 156
i_am_jorf Avatar answered Oct 18 '22 16:10

i_am_jorf


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.

like image 27
Boldewyn Avatar answered Oct 18 '22 17:10

Boldewyn