1

I wrote a callback function to record mouse event:

var body = document.querySelector("body");
var callback = function (e) {
    console.log(e.type);
}

body.addEventListener('mousedown', callback, false);
body.addEventListener('mouseup', callback, false);
body.addEventListener('mousemove', callback, false);

what confused me is, when I do a click, in addition to triggering the mousedown and mouseup events, it will trigger mousemove event too.

Watch the demo here: http://jsfiddle.net/r6Gqn/1/

Why is it that I do not move the mouse, but trigger the mousemove event? How can I stop triggering the mousemove event?

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
hh54188
  • 14,027
  • 31
  • 107
  • 178

1 Answers1

0

I have made a workaround using jQuery (easier for me, I am sure it can be adapted for plain js). It seems like no one believes this is happening, but it happens for me in Chrome as well. (I am holding the mouse in the air, it cannot possibly be moving.) There is an existing bug for it for Chrome. I could not reproduce it in FireFox.

Anyway, here is the fix I came up with. There is a demo here: JsFiddle

$('#box').bind('mousemove', moved);

function moved() {
    console.log('mousemove');
}

$('#box').mousedown(function (ev) {
    console.log("mousedown");
});

$('#box').mouseup(function () {
    $("#box").unbind("mousemove");
    console.log("mouseup");
    setTimeout(function () {
        $("#box").bind("mousemove", moved);        
    }, 1);
});

Basically, this modifies the mouseup event to unbind mousemove, wait a very short time, then rebind it.

Gray
  • 6,916
  • 2
  • 28
  • 49