Sometimes, we want to detect a long touch pressure with JavaScript for Android and iPhone.
In this article, we’ll look at 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?
To detect a long touch pressure with JavaScript for Android and iPhone, we listen to the touchstart and touchend events.
For instance, we write
let touchStartTimeStamp = 0;
let touchEndTimeStamp = 0;
const onTouchStart = (e) => {
  touchStartTimeStamp = e.timeStamp;
};
const onTouchEnd = (e) => {
  touchEndTimeStamp = e.timeStamp;
  console.log(touchEndTimeStamp - touchStartTimeStamp);
};
window.addEventListener("touchstart", onTouchStart, false);
window.addEventListener("touchend", onTouchEnd, false);
to call addEventListener to listen for the touchstart and touchend events on window.
Then we get the timeStamp of when the touch starts from onTouchStart.
And we get the timeStamp of when the touch ends from onTouchEnd.
We also subtract touchEndTimeStamp by touchStartTimeStamp to get the touch duration in milliseconds.
Conclusion
To detect a long touch pressure with JavaScript for Android and iPhone, we listen to the touchstart and touchend events.
