Question

I need to determine whether a movable div was just clicked or dragged. I know there are multiple solutions to this problem, but due to the nature of the entire project and the scripts I am using, I cannot apply other ways, since they interfere with some jQuery methods.

This is my code:

$('.textFieldOuter').mousedown(function(e) {
    var oldMousePos = [e.pageX,e.pageY];
    fieldMouseDown(oldMousePos,$(this));
});

function fieldMouseDown(oldMousePos,field) {
    field.bind("mouseup",function(e) {
        var newMousePos = [e.pageX,e.pageY];
        console.log("oldMousePos: " + oldMousePos);
        console.log("newMousePos: " + newMousePos);
        if(oldMousePos == newMousePos) { console.log("Mouse did NOT move!") }
        else if(oldMousePos != newMousePos) { console.log("Mouse MOVED!") }
        $(this).unbind("mouseup");
    });
}

Why does this code always log "Mouse MOVED!" when in fact, the mouse is just clicked and not moved before the "mouseup" event? In the console it's even visible, that the variables "oldMousePos" and "newMousePos" store exactly the same coordinates, if the mouse is not dragged, yet "Mouse MOVED!" is logged. Why is this?

Was it helpful?

Solution

You comparing two Arrays here, and Arrays are Objects: hence both == and === in JavaScript return true only if both operands are in fact the same Object.

But it's not the case here, as there are two different Arrays: first, oldMousePos, is created in mousedown handler, and second, newMousePos, is created in fieldMouseDown function.

To compare them, compare each field separately:

if ( oldMousePos[0] === newMousePos[0] && oldMousePos[1] === newMousePos[1] ) {
  // ..
}

... or just send each coordinate as a separate param into that function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top