Javascript: is it possible to hold the mouse position outside the event handler?

I want to get the mouse position in a timeout callback.

As far as I can tell, this cannot be done directly. One job might be to set the onmousemove event to document.body and save that position, retrieving it later. It would be quite expensive, but it is not the cleanest of approaches.

+4
source share
3 answers

I think you will have to do the same as @Oli, but if you use jQuery it will be much easier.

http://docs.jquery.com/Tutorials:Mouse_Position

<script type="text/javascript"> jQuery(document).ready(function(){ $().mousemove(function(e){ $('#status').html(e.pageX +', '+ e.pageY); }); }) </script> 
+2
source

There is no direct answer, but, as you say correctly, you can attach events to everything and interrogate accordingly. It would be expensive to do some serious programming on every instance of onmousemove, so that you could better create several zones around the page and poll the onmouseover event.

Another alternative could be (and I'm not sure if this works at all) to set a repeating timeout:

  • Add onmousemove body handler
  • Move the whole page (for example, change the upper edge of the body)
  • when the onmousemove handler starts, gets the position and removes the handler. You may need a timeout on this event (when the mouse left the viewport)

Uberhack, but that might work.

0
source

As you described, the easiest way to do this is to install the onmousemove event handler on the body. This is cheaper than you think: very few calculations are done to store coordinates, and the event fires 50 to 100 times per second when the mouse is moved. And I suspect that the average user will not move their mouse constantly while browsing the web.

The following script helps in counting event handlers; on my machine, moving the mouse to Firefox, this added 5% to 10% to the use of my processor.

 <script type="text/javascript"> jQuery(document).ready(function(){ var count = 0; $().mousemove(function(e){ count += 1; }); $().click(function(e){ $('#status').html(count); }); }); </script> 
0
source

All Articles