tic
tic

Reputation: 4189

javascript: long click for a bookmarklet

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?

Upvotes: 4

Views: 943

Answers (3)

DG.
DG.

Reputation: 3517

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.

Upvotes: 0

nre
nre

Reputation: 1299

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();
    }
});

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270599

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>

Here it is in action in jsfiddle

Upvotes: 7

Related Questions