views:

877

answers:

3

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

As far as I can tell, this isn't possible, though one work around might be to set an onmousemove event on document.body when one needs this information and to save this position somewhere. This would be rather expensive however, and is rather hackish.

A: 

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.

Oli
interesting idea.
enobrev
+1  A: 

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>
Sikachu
Load up a task manager and look at the CPU graph while you move the mouse. With Firefox3 on Linux, it almost consumes the whole CPU while moving fast. A time-based poll (still using most of this code) would perform a lot better.
Oli
A: 

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>
Alex Morega