This should work well. Similar to the accepted answer (though using jQuery), but the isDragging
flag is only reset if the new mouse position differs from that on mousedown
event. Unlike the accepted answer, that works on recent versions of Chrome, where mousemove
is fired regardless of whether mouse was moved or not.
var isDragging = false;
var startingPos = [];
$(".selector")
.mousedown(function (evt) {
isDragging = false;
startingPos = [evt.pageX, evt.pageY];
})
.mousemove(function (evt) {
if (!(evt.pageX === startingPos[0] && evt.pageY === startingPos[1])) {
isDragging = true;
}
})
.mouseup(function () {
if (isDragging) {
console.log("Drag");
} else {
console.log("Click");
}
isDragging = false;
startingPos = [];
});
You may also adjust the coordinate check in mousemove
if you want to add a little bit of tolerance (i.e. treat tiny movements as clicks, not drags).