Javascript: Is it possible to get hold of the mouse position outside of an event handler?

StackOverflow https://stackoverflow.com/questions/433409

  •  10-07-2019
  •  | 
  •  

Question

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

As far as I can tell, this can't be done directly. One work around might be to set an onmousemove event on document.body and to save this position, fetching later. This would be rather expensive however, and isn't the cleanest of approaches.

Was it helpful?

Solution

I think you'll have to do the same thing as @Oli, but then if you're using jQuery, it would be much more 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>

OTHER TIPS

The direct answer is no but as you correctly say, you can attach events to everything and poll accordingly. It would be expensive to do serious programming on every onmousemove instance so you might find it better to create several zones around the page and poll for a onmouseover event.

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

  1. Add a onmousemove handler to body
  2. Move the entire page (eg change the body's margin-top)
  3. when the onmousemove handler triggers, get the position and remove the handler. You might need a timeout on this event too (for when the mouse is out of the viewport)

Uberhack but it might work.

As you described, the most straightforward way to do it is setting the onmousemove event handler on the body. It's less expensive than you think: very little computation is done to store the coordinates, and the event gets fired 50 to 100 times a second when the mouse moves. And I suspect a typical user won't move their mouse constantly when viewing a web page.

The following script helps with counting event handlers; on my machine, moving the mouse around in Firefox, this added 5% to 10% to my CPU usage.

<script type="text/javascript">
jQuery(document).ready(function(){
    var count = 0;
    $().mousemove(function(e){ count += 1; }); 
    $().click(function(e){ $('#status').html(count); });
}); 
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top