views:

297

answers:

3

How can I retrieve the mouse location outside of it's assigned event handler function

For example, if Event.MOUSEMOVE = somefuction, how do I say...

someOtherFunction( maybeSomeParams )
{
    getCurrentMouseLocn();
}

or

someOtherFunction( maybeSomeParams )
{
    mouseXLocn = ?; 
    mouseYLocn = ?;
}
+1  A: 

The easiest way is to capture the mouse move event and save the position to a global variable.

If it's already captured you can do:

var oldFunction = document.onmousemove;
document.onmousemove = function(e)
{
    // save x & y here...

    return oldFunction(e);
}
Greg
A: 

With jQuery you can have mouse position in any events:

$('#example').click(function(e){
   var x = e.pageX;
   var y = e.pageY;
   // ...
});

More infos here: http://docs.jquery.com/Tutorials:Mouse_Position This can help. Otherwise use mousemove event to store the latest position x/y in global variables.

GiDo
Did you read his question?
vsync
Ooh, you are right! I didn't understand completly the question.In this case, one way it to use global variable.
GiDo
+1  A: 

Unfortunately there is no way to retrieve the location of the mouse cursor outside of an event handler. One option do you have is to register an event handler for the onmousemove event and store the coordinates in a global(ish) variable.

Using plain old javascript the following code should do the trick for Safari and FF3.

var coords = {x: NaN, y: NaN};

...

if (coords.x === ... && coords.y === ...) {
   /* insert your magic here */
}

...

window.addEventListener('mousemove', function(e) { 
    coords.x = e.clientX;
    coords.y = e.clientY;
}, true);

In short, an event listener (handler) is registered for the "onmousemove" event. When the event fires the anonymous function is called with the event. The event contains several properties, two of which are clientX and clientY. These are the coordinates of the mouse relative to the window, not the top of the document. These coordinates are placed in a variable that is accessible to both the handler and the code that needs the coordinates. This could be a global or a closed-over variable of some kind.

I should note that typically javascript implementations within the browsers are single-threaded. Simply put this means that the values contained in the coords variable may not always be up to date if the mouse has moved since the last time the event handler was called.

Bryan Kyle