VisioN VisioN - 1 year ago 90
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:

mousemove: function(e) {
click: function(e) {

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

>> ...
>> click
>> move


Note, that
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
event only.

Answer Source

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) {

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download