Get the duration of a touch in javascript
12,286
Solution 1
$('#element').each(function() {
var timeout,
longtouch;
$(this).bind('touchstart', function() {
timeout = setTimeout(function() {
longtouch = true;
}, 1000);
}).bind('touchend', function() {
if (longtouch) {
// It was a long touch.
}
longtouch = false;
clearTimeout(timeout);
});
});
The fiddle works with a long click.
Solution 2
Take a look at jQuery mobile http://jquerymobile.com/demos/1.0a4.1/#docs/api/events.html
It has tap, and taphold events, which sounds like it might fit your needs.
Author by
cmplieger
Updated on June 17, 2022Comments
-
cmplieger almost 2 years
Is it possible to get the duration of a touch using javascript on ios devices (and others if possible)? I would like to differentiate a long press from a short "click" press on an iphone webapp.
Thank you for your help!
-
Scott Harwell almost 13 yearsI'm not sure whether this can happen, but you may find some answers by looking at some jQuery touch options. Most of all, I would check out Apple's Safari dev center for answers. If it can happen natively, it will tell you how to do so there.
-
Admin almost 13 yearsthe relevant w3c docs for touch events: dvcs.w3.org/hg/webevents/raw-file/tip/touchevents.html
-
-
cmplieger almost 13 yearshey thanks! with ontouchstart and ontouchend i can make this into touch events I guess :). Let me try.
-
Alxandr almost 13 yearsWell, then, here's how jQuery do it: pastie.org/1919250, shouldn't be too hard to decode. It seems they are using vmousedown-events, which might be a virtual-mouse-down event supported by smartphones, or something else altogether (customely made by jQuery, what do I know), but it should be enough to get you started at least.
-
Alxandr almost 13 yearsThis does not work on FF on android at least. I get "short-touch" every time, no-matter how long I press...
-
RobG almost 13 years@SnippetSpace - touchstart and touchend are touch events. As Alex shows, start a timeout when you get a touchstart, then when you get a touchend event see how long it took. Note that you will also get a click and possibly other events related to the same gesture.