Fetch mouse cells outside of event handler

How can I get the mouse location outside of the assigned event handler function

For example, if Event.MOUSEMOVE = somefuction

, as I can tell ...

someOtherFunction( maybeSomeParams )
{
    getCurrentMouseLocn();
}

      

or

someOtherFunction( maybeSomeParams )
{
    mouseXLocn = ?; 
    mouseYLocn = ?;
}

      

0


a source to share


3 answers


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

If it is already captured, you can do:



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

    return oldFunction(e);
}

      

+1


a source


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

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 available to both the handler and the code that needs the coordinates. It can be a global or a private variable of some type.

It should be noted that, as a rule, javascript implementations within browsers are single-threaded. In simple terms, this means that the values ​​contained in a variable coords

may not always be updated if the mouse has moved since the last call to the event handler.

+1


a source


With jQuery, you can have the mouse position on any events:

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

      

More info here: http://docs.jquery.com/Tutorials:Mouse_Position This might help. Otherwise, use mousemove to store the last x / y position in globals.

0


a source







All Articles