Javascript: long click for bookmarklet

I need to recognize a long click in a JavaScript shortcut. Thus, I can not use jQuery, neither the onclick () event, nor the like. Is it possible, and how?

+4
source share
3 answers

onmousedown , call setTimeout() for the whole long click. If the timeout is allowed to expire, it will call its function to do whatever you hoped to do with a long press. However, onmouseup you will cancel setTimeout() if it has not expired.

 <script type='text/javascript'> // t will hold the setTimeout id // Click for 1 second to see the alert. var t; </script> <button onmousedown='t=setTimeout(function(){alert("hi");}, 1000);' onmouseup='clearTimeout(t);'>Clickme</button> 

Here it is in action in jsfiddle

+7
source

Not a long click, just a click, where are the mousedown and mouseclick far removed from each other? To solve this, you can simply measure the time it takes from the mousedown event to the click event and check if it is, for example. longer than two seconds (or whatever you want).

You can access the current milliseconds from 01/01/1970 via new Date().getTime() . Given that I would intuitively check for a "long click".

 $(".selector").mousedown(function() { $(this).data("timestamp", new Date().getTime()); }).click(function(event) { var e = $(this); var start = e.data("timestamp"); e.removeData("timestamp"); if (start && new Date().getTime() - start > YOUR_DESIRED_WAIT_TIME_IN_MILLISECONDS) { // Trigger whatever you want to trigger } else { event.preventDefault(); event.stopPropagation(); } }); 
+1
source

Late answer, but instead of a click / long click, in order to provide two different actions, you may need to click / double click.

First click: Record the time and then the timer to perform action1 in 500 milliseconds.

Second click: if the time since the last click is short, cancel the timer and perform step 2. If the time from the last click is long, this is the first click.

Nothing prevents you from using a triple click, etc.

0
source

All Articles