To know the difference in horizontal and vertical, you must work on the X and Y axes. This would be so if we were to use the logic of your code.
var ts_x;
var ts_y;
$(document).bind('touchstart', function(e) {
ts_x = e.originalEvent.touches[0].clientX;
ts_y = e.originalEvent.touches[0].clientY;
});
$(document).bind('touchend', function(e) {
var td_x = e.originalEvent.changedTouches[0].clientX - ts_x;
var td_y = e.originalEvent.changedTouches[0].clientY - ts_y;
// O movimento principal foi vertical ou horizontal?
if( Math.abs( td_x ) > Math.abs( td_y ) ) {
// é horizontal
if( td_x < 0 ) {
// esquerda
} else {
// direita
}
} else {
// é vertical
if( td_y < 0 ) {
// cima
} else {
// baixo
}
});
A pure JS code follows the original properties of the event, pageX
and pageY
:
var ts_x;
var ts_y;
document.addEventListener('touchstart', function(e) {
e.preventDefault();
var touch = e.changedTouches[0];
ts_x = touch.pageX;
ts_y = touch.pageY;
}, false);
document.addEventListener('touchmove', function(e) {
e.preventDefault();
var touch = e.changedTouches[0];
td_x = touch.pageX - ts_x; // deslocamento na horizontal
td_y = touch.pageY - ts_y; // deslocamento na vertical
// O movimento principal foi vertical ou horizontal?
if( Math.abs( td_x ) > Math.abs( td_y ) ) {
// é horizontal
if( td_x < 0 ) {
// é para esquerda
} else {
// direita
}
} else {
// é vertical
if( td_y < 0 ) {
// cima
} else {
// baixo
}
}
}, false);
To increment the code, you can check if the movement has passed a certain distance, to ignore touches on the screen by adding something like this:
if( Math.max( Math.abs( td_x ), Math.abs( td_y ) ) > 10 ...
Note: I used the event touchend
instead of touchmove
. See which one is most suitable for end use. The end is only triggered when the move is terminated, move can be fired a number of times during dragging.