How to determine the direction of the touchmove

Asked

Viewed 657 times

4

How in javascript/jquery to know which direction is the touchmove ?

Example:

    var ts;
    $(document).bind('touchstart', function(e) {
    ts = e.originalEvent.touches[0].clientY;
    });

    $(document).bind('touchmove', function(e) {
    var te = e.originalEvent.changedTouches[0].clientY;
    if (ts > te) {
    //cima
    } else {
    //baixo
    }
    });

Now missing left and right...

1 answer

5


To know the difference horizontally and vertically, you should 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
      }
 });

Follow a pure JS code, using the original event properties, 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: used the event touchend in place of touchmove. See which is the most suitable for end use. The end is only fired when closing the movement, the move can be triggered a number of times during the "drag".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.