VisioN VisioN - 4 months ago 16
Javascript Question

What to do if "mousemove" and "click" events fire simultaneously?

I don't know whether it is only Chrome problem (can't check now), however let's try the following piece of code, where we bind two events to some element:

$("div").on({
mousemove: function(e) {
console.log("move");
},
click: function(e) {
console.log("click");
}
});


If we try to click the element, we'll find that for some reason
mousemove
event fires immediately after click, so in console we have:

>> ...
>> click
>> move


DEMO: http://jsfiddle.net/gKqVt/

Note, that
mousedown
and
mouseup
events work by the same scenario.

I saw many questions on SO about the same problem, but none (in my search) gave the straightforward idea what to do in order to fire the
click
event only.

Answer

This behavior is odd, and it doesn't seem to occur universally (happens in Chrome/IE for me, but not FFX). I think you haven't gotten a straight answer because there isn't one really.

It's possible that the mouse is moved very slightly by the click action, but that's probably not it. Could just be a browser quirk. These don't even seem to be the same event since stopImmediatePropagation in click doesn't stop mousemove from firing. If you focus the element and hit a keyboard button, it will actually trigger click and only click.

Since this is so quirky, it seems like the only way to deal with it is times. As much of a kludge as this is, I do notice that click happens one millisecond before mousemove, so you could get close by comparing the click timestamp + 2 (or 10):

mousemove: function(e) {
    if ($(this).data('lastClick') + 10 < e.timeStamp) {

http://jsfiddle.net/gKqVt/3/

This is very specific, though. You should consider not having behavior that occurs immediately on mousemove since it's so frequent.