[ACCEPTED]-Determine mouse position outside of events (using jQuery)?-position

Accepted answer
Score: 47

Not possible. You can however use the same 4 approach in the tutorial to store the position 3 in a global variable and read it outside 2 the event.

Like this:

      window.mouseXPos = e.pageX;
      window.mouseYPos = e.pageY;

You can now use window.mouseXPos and 1 window.mouseYPos from anywhere.

Score: 29

This started as a comment on Chetan Sastry's answer, but I realized 17 it also might be worth posting as an answer:

I'd 16 be careful about having a document-level, always-running 15 mousemove event, even if you're only polling for 14 cursor position. This is a lot of processing 13 and can bog down any browser, particularly 12 slower ones like IE.

A problem like this 11 almost certainly raises the question of 10 design decision: if you don't need to handle 9 a mouse event to poll for the cursor position, do 8 you really need the cursor position? Is 7 there a better way to solve the problem 6 you're trying to solve?

Edit: even in Safari 5 4, which is (understatement) very fast, that single 4 mousemove event makes every interaction with that 3 tutorial page noticeably choppy for me. Think 2 about how that will affect users' perceptions 1 of your site or application.

Score: 10

This function will decrease the impact on 6 UI performance by only getting the mouse 5 position at an interval:

function getMousePosition(timeoutMilliSeconds) {
    // "one" attaches the handler to the event and removes it after it has executed once 
    $(document).one("mousemove", function (event) {
        window.mouseXPos = event.pageX;
        window.mouseYPos = event.pageY;
        // set a timeout so the handler will be attached again after a little while
        setTimeout(function() { getMousePosition(timeoutMilliSeconds) }, timeoutMilliseconds);

// start storing the mouse position every 100 milliseconds

Just as in the 4 other answer "You can now use window.mouseXPos and window.mouseYPos from 3 anywhere."

You lose a little accuracy as 2 the mouse move won't be detected during 1 the intervals.

Score: 2

I have try @Chetan Sastry 's soulution,but 3 it does't works.(I'm using jQuery 1.6.4). I 2 change the code and then i works now. Here 1 is my code. I hope this will help.

          window.mouseXPos = e.pageX;
          window.mouseYPos = e.pageY;

More Related questions