I need to recognize a long click in a JavaScript bookmarklet. So, I cannot use jQuery, neither onclick() event and similar. Is it possible, and how?
3 Answers
onmousedown
, call setTimeout()
for the duration of your long click. If the timeout is allowed to expire, it will call its function to do whatever you hoped to do on the long click. However, onmouseup
you cancel the setTimeout()
if it has not yet 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>

- 267,341
- 46
- 444
- 390
-
The example is fine. But in a bookmarklet I cannot use a button, isn't it? – tic Aug 24 '11 at 12:27
-
@tic It doesn't have to be a button. That was just the simplest example. Any element that supports onmousedown/onmouseup will work. ``, ``, whatever you need– Michael Berkowski Aug 24 '11 at 12:52
-
Maybe I've not done my question very well. I want a bookmarklet which is able to do two different things: one if the user clic it, and another one if the user makes a long clic on it. It seems to me that I cannot use any element of a "normal" web page, as button, div, etcetera. – tic Aug 26 '11 at 08:43
-
@tic I don't think it's going to be possible then - a bookmarklet can only run a single function, and can't really receive any mouse events since it isn't a page element – Michael Berkowski Aug 26 '11 at 12:50
Isn't a long click just a click where mousedown
and mouseclick
events are considerably long away from each other? In order to solve that you could just measure the time it takes from a mousedown
event to the click event and check if it is, e.g. longer than two seconds (or whatever you desire).
You can access the current milliseconds since 01.01.1970 via new Date().getTime()
. Given that I would intuitively check a "long click" like that.
$(".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,299
- 11
- 24
-
-
This is done using jQuery. Was not sure if your requirement was actually NOT to use jQuery or if this one helped you, too. – nre Aug 26 '11 at 16:34
Late reply, but instead of click / long click to provide two different actions, you might want to consider click / double click.
First click: Record time and then timer to perform action1 in 500 miliseconds.
Second click: If time since last click is short, cancel timer and perform action2. If time since last click is long, then this is a first click.
Nothing stops you from using triple click, etc.

- 3,417
- 2
- 23
- 28