6

I've read about issues where the mousemove event is fired twice in Safari/Webkit, but the problem I'm facing is that mousemove fires even when the mouse is not moved. That is: it already fires when the mouse cursor is positioned above the context that the event is attached to when the page is loaded/refreshed. And because I'm attaching it to document (entire viewport of the browser), it fires right away in Safari. I've tried to attach it to the html element, to the body and to a wrapper div. No change.

$(document).bind('mousemove', function() {
  alert('Mouse moved!');
  $(document).unbind('mousemove');
});

Is does work ok in other browsers. Anyone seeing what I'm doing wrong? Thanks.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Roel
  • 335
  • 1
  • 3
  • 10
  • I have the same problem. Cmd, ctrl alt, shift and caps lock also fires the mousemove event (safari 4 on mac). Try it out here: http://www.quirksmode.org//js/events/mousemove.html – Fred Bergman Apr 12 '10 at 13:17

1 Answers1

1

I know it’s a dirty hack, but at least this is something: simply execute the callback function the second time mousemove is fired.

var $document = $(document), i = 0;
$document.bind('mousemove', function() {
 if (++i > 1) {
  alert('Mouse moved!');
  $document.unbind('mousemove');
 };
});

Demo: http://fiddle.jshell.net/Yz5Bd/show/light/

For what it’s worth, Safari is not the only browser firing mousemove on page load — IE does it too. Anyhow, people using other browsers won’t notice the ‘delay’, since it’s virtually impossible to move your mouse only one pixel.

Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248