user47741
user47741

Reputation: 3015

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

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.

Upvotes: 4

Views: 2581

Answers (3)

Alex Morega
Alex Morega

Reputation: 4228

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>

Upvotes: 0

sikachu
sikachu

Reputation: 1221

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>

Upvotes: 2

Oli
Oli

Reputation: 239790

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.

Upvotes: 0

Related Questions