Javascript: Long Click For A Bookmarklet
Solution 1:
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.
<scripttype='text/javascript'>// t will hold the setTimeout id// Click for 1 second to see the alert.var t;
</script><buttononmousedown='t=setTimeout(function(){alert("hi");}, 1000);'onmouseup='clearTimeout(t);'>Clickme</button>
Solution 2:
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", newDate().getTime());
}).click(function(event) {
var e = $(this);
var start = e.data("timestamp");
e.removeData("timestamp");
if (start && newDate().getTime() - start > YOUR_DESIRED_WAIT_TIME_IN_MILLISECONDS) {
// Trigger whatever you want to trigger
} else {
event.preventDefault();
event.stopPropagation();
}
});
Solution 3:
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.
Post a Comment for "Javascript: Long Click For A Bookmarklet"