Currently we can use different types of events to control a touch gesture on a mobile device using javascript, but unfortunately they are not enough to detect all the huge amount of behaviours that an User could do with a touch gesture.
Some of the events that you can catch having everything under control are touchstart, touchmove, touchend and touchcancel.
In one of my projects I needed to detect the ‘Tap’ event that is a bit different from the ‘touchstart’ event *, so I found this solution that works pretty well, and here you can get the code.
*The Tap event should not be confused with the click because they are two things completely different
var $touchArea = $('#touchArea'),
touchStarted = false, // detect if a touch event is sarted
currX = 0,
currY = 0,
cachedX = 0,
cachedY = 0;
//setting the events listeners
$touchArea.on('touchstart mousedown',function (e){
e.preventDefault();
// caching the current x
cachedX = e.pageX;
// caching the current y
cachedY = e.pageY;
// a touch event is detected
touchStarted = true;
$touchArea.text('Touchstarted');
// detecting if after 200ms the finger is still in the same position
setTimeout(function (){
currX = e.pageX;
currY = e.pageY;
if ((cachedX === currX) && !touchStarted && (cachedY === currY)) {
// Here you get the Tap event
$touchArea.text('Tap');
}
},200);
});
$touchArea.on('touchend mouseup touchcancel',function (e){
e.preventDefault();
// here we can consider finished the touch event
touchStarted = false;
$touchArea.text('Touchended');
});
$touchArea.on('touchmove mousemove',function (e){
e.preventDefault();
if(touchStarted) {
// here you are swiping
$touchArea.text('Swiping');
}
});
touchStarted = false, // detect if a touch event is sarted
currX = 0,
currY = 0,
cachedX = 0,
cachedY = 0;
//setting the events listeners
$touchArea.on('touchstart mousedown',function (e){
e.preventDefault();
// caching the current x
cachedX = e.pageX;
// caching the current y
cachedY = e.pageY;
// a touch event is detected
touchStarted = true;
$touchArea.text('Touchstarted');
// detecting if after 200ms the finger is still in the same position
setTimeout(function (){
currX = e.pageX;
currY = e.pageY;
if ((cachedX === currX) && !touchStarted && (cachedY === currY)) {
// Here you get the Tap event
$touchArea.text('Tap');
}
},200);
});
$touchArea.on('touchend mouseup touchcancel',function (e){
e.preventDefault();
// here we can consider finished the touch event
touchStarted = false;
$touchArea.text('Touchended');
});
$touchArea.on('touchmove mousemove',function (e){
e.preventDefault();
if(touchStarted) {
// here you are swiping
$touchArea.text('Swiping');
}
});
Here it is the result or you can check the demo directly here :
An observation, – I see Jquery code and not pure javascript.
Yeah you are right, but:
I am sorry if this article wasn’t useful for you, but anyway thanks for your feedback
Cheerio
super useful. thanks for sharing