Leem Leem - 2 months ago 10
Javascript Question

How to distinguish mouse "click" and "drag"

I use

jQuery.click
to handle the mouse click event on Raphael graph, meanwhile, I need to handle mouse
drag
event, mouse drag consists of
mousedown
,
mouseup
and
mousemove
in Raphael.

It is difficult to distinguish
click
and
drag
because
click
also contain
mousedown
&
mouseup
, How can I distinguish mouse "click" & mouse "drag" then in Javascript?

Answer

I think the difference is that there is a mousemove between mousedown and mouseup in a drag, but not in a click.

You can do something like this:

var flag = 0;
var element = xxxx;
element.addEventListener("mousedown", function(){
    flag = 0;
}, false);
element.addEventListener("mousemove", function(){
    flag = 1;
}, false);
element.addEventListener("mouseup", function(){
    if(flag === 0){
        console.log("click");
    }
    else if(flag === 1){
        console.log("drag");
    }
}, false);
Comments