I'm in need of a function that figures out if the user is clicking, double-clicking or dragging the mouse.
Since it's all happening in the same canvas using the normal events doesn't work. I found this through google:
It is inadvisable to bind handlers to both the click and dblclick
events for the same element. The sequence of events triggered varies
from browser to browser, with some receiving two click events and
others only one. If an interface that reacts differently to single-
and double-clicks cannot be avoided, then the dblclick event should be
simulated within the click handler. We can achieve this by saving a
timestamp in the handler, and then comparing the current time to the
saved timestamp on subsequent clicks. If the difference is small
enough, we can treat the click as a double-click.
How could I achieve this in a good way?
First see if the click is pressed (for drag)? When it is released treat it as a click? and then if clicked again doubleclick?
How can I translate this to code? Help appreciated.
Something like the following should get you started, I'm using jQuery just to make it easier to show, this can be implemented with straight JS, it's just a lot of noise
$(function() {
var doubleClickThreshold = 50; //ms
var lastClick = 0;
var isDragging = false;
var isDoubleClick = false;
$node = ("#mycanvas");
$node.click(function(){
var thisClick = new Date().getTime();
var isDoubleClick = thisClick - lastClick < doubleClickThreshold;
lastClick = thisClick;
});
$node.mousedown(function() {
mouseIsDown = true;
});
$node.mouseUp(function() {
isDragging = false;
mouseIsDown = false;
});
// Using document so you can drag outside of the canvas, use $node
// if you cannot drag outside of the canvas
$(document).mousemove(function() {
if (mouseIsDown) {
isDragging = true;
}
});
});
I would probably work around this by putting a timer in the click event to check for another click.
time = 0
if(new Date().getTime() < time + 400) {
// Double click
throw new Error("Stop execution");
}
if(!!time)
throw new Error("Stop execution");
time = new Date().getTime();
// Single click
Something like that. Untested, and I can't think right now for some odd reason.