thegreyspot
thegreyspot

Reputation: 4109

Jquery mousemove() gets activated without a mouse movement

I am trying to do a google.com like fade in (Cept i want to fade out text)

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
  $(document).ready(function() {
    $("html").mousemove(function () {
      $("p").fadeOut("slow");
    });
  });
</script>

With that code, my fade out gets automatically activated although I have not moved the mouse. Happens in all browsers. Any tips?

Upvotes: 3

Views: 2715

Answers (3)

alexcoco
alexcoco

Reputation: 6665

It seems that if the page loads and the mouse is present on the page once the page has loaded it will fire an event. Try hiding your mouse from the page by leaving it over the address bar or somewhere over the menu at the top of your browser, refresh the page with F5 and notice that the event is not fired. Similarly, try refreshing with F5 and immediately right click on the page. Keep your mouse over the page but make sure that the context menu is still open. Once the page has loaded, without moving your mouse at all, hit the Escape key on your keyboard so the mouse will exit the context menu and return to the page. The mouse has not moved but has been detected on the page and the event is triggered.

Tested in Chrome 5 on Windows 7. Too lazy to try another browser but I assume it's the same thing.

Upvotes: 1

Craig
Craig

Reputation: 36816

Are you sure there is not 'micro movements'? Sometimes an optical mouse can causes movements to register just with dust or dirt.

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630379

Since the event fires once initially and mousemove fires every time you move it a pixel, you could just ignore the very first (possibly automatic, depending on browser) mousemove event to get the effect you want, like this:

$(function() {
  var moveCount = 0;
  $("html").mousemove(function () {
    if(moveCount++ === 0) return; //first run?
    $("p").fadeOut("slow");
    $(this).unbind('mousemove'); //unbind this, no need to stick around
  });
});​

You can try a demo here, all we're doing is ignoring the very first firing of the mousemove event, after that we do the fade and unbind this handler so that it doesn't run for future mousemove firings, just cleaning up.

Upvotes: 5

Related Questions