Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect a long touch pressure with javascript for android and iphone?

How to detect a long touch pressure with javascript for android and iphone? native javascript or jquery...

I want something that sound like :

<input type='button' onLongTouch='myFunc();' /> 
like image 258
Christophe Debove Avatar asked May 26 '11 13:05

Christophe Debove


2 Answers

The problem with using Touch End to detect the long touch is it won't work if you want the event to fire after a certain period of time. It is better to use a timer on touch start and clear the event timer on touch end. The following pattern can be used:

var onlongtouch;  var timer; var touchduration = 500; //length of time we want the user to touch before we do something  touchstart() {     timer = setTimeout(onlongtouch, touchduration);  }  touchend() {      //stops short touches from firing the event     if (timer)         clearTimeout(timer); // clearTimeout, not cleartimeout.. }  onlongtouch = function() { //do something }; 
like image 115
Joshua Avatar answered Oct 03 '22 04:10

Joshua


Here is an extended version of Joshua answer, as his code works well till user doesn't perform multitouch (you can tap screen with two fingers and function will be triggered two times, 4 fingers - 4 times). After some additional test scenarios I even triggered possibility to touch very freequently and receive function executing after each tap.

I added variable named 'lockTimer' which should lock any additional touchstarts before user trigger 'touchend'.

var onlongtouch;   var timer;  var touchduration = 800; //length of time we want the user to touch before we do something    function touchstart(e) {      e.preventDefault();      if (!timer) {          timer = setTimeout(onlongtouch, touchduration);      }  }    function touchend() {      //stops short touches from firing the event      if (timer) {          clearTimeout(timer);          timer = null;      }  }    onlongtouch = function() {       timer = null;      document.getElementById('ping').innerText+='ping\n';   };    document.addEventListener("DOMContentLoaded", function(event) {       window.addEventListener("touchstart", touchstart, false);      window.addEventListener("touchend", touchend, false);  });
<div id="ping"></div>
like image 21
SLoN1ck Avatar answered Oct 03 '22 03:10

SLoN1ck