Javascript, click, double click and drag the same item

I need a function that determines whether the user clicks by double-clicking or dragging the mouse.

Since everything that happens on one canvas using ordinary events does not work. I found this via google:

It is not recommended to associate handlers with both a click and dblclick events for the same element. The sequence of triggered events varies from browser to browser, with some receiving two click events and others receiving only one. If an interface that responds differently to single and double clicks cannot be avoided, then the dblclick event should be modeled in the click handler. We can achieve this by storing the timestamp in the handler, and then comparing the current time with the saved timestamp on subsequent clicks. If the difference is small enough, we can consider the click as a double click.

How can I achieve this in a good way?

First see if a click is clicked (for drag and drop)? When it's released, treat it like a click? and then, if you double-click, double-click?

How can I translate this into code? Help evaluate.

+2
javascript html5 event-handling canvas
source share
2 answers

Something like the following should get you started, I use jQuery to simplify the display, it can be implemented using direct 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; } }); }); 
+4
source share

I will probably get 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. Unverified, and I can’t think now for some strange reason.

0
source share

All Articles