How to get direction and distance using jQuery Mobiles swipe event

Is it possible to get the direction and distance in a callback function when using the jQuery Mobiles event? I did not find anything about this in the official white papers .

TouchSwipe is a good alternative, but I need a jQuery Mobile tap event form, and I don't want to include two libraries.

+6
source share
3 answers

Working example: http://jsfiddle.net/Gajotres/K69AJ/

This example was executed using jQuery Mobile events, so it will only work with jQuery Mobile. Tested on Windows and Android.

Vmouse events are created to bridge the gap between desktop and mobile browsers.

Also pay attention to this line:

 event.preventDefault(); 

This is necessary for the Android platform, the platform has an unpleasant error with the detection of touch movements. Bug Report: http://code.google.com/p/android/issues/detail?id=19827

 var gnStartX = 0; var gnStartY = 0; var gnEndX = 0; var gnEndY = 0; $(document).on('vmousedown', function(event){ gnStartX = event.pageX; gnStartY = event.pageY; event.preventDefault(); }); $(document).on('vmouseup', function(event){ gnEndX = event.pageX; gnEndY = event.pageY; var distance = Math.ceil(nthroot(Math.pow((gnEndX - gnStartX),2) + Math.pow((gnEndY - gnStartY),2), 2)); if(Math.abs(gnEndX - gnStartX) > Math.abs(gnEndY - gnStartY)) { if(gnEndX > gnStartX) { alert("Swipe Right - Distance " + distance + 'px'); } else { alert("Swipe Left - Distance " + distance + 'px'); } } else { if(gnEndY > gnStartY) { alert("Swipe Bottom - Distance " + distance + 'px'); } else { alert("Swipe Top - Distance " + distance + 'px'); } } event.preventDefault(); }); function nthroot(x, n) { try { var negate = n % 2 == 1 && x < 0; if(negate) x = -x; var possible = Math.pow(x, 1 / n); n = Math.pow(possible, n); if(Math.abs(x - n) < 1 && (x > 0 == n > 0)) return negate ? -possible : possible; } catch(e){} } 
+8
source

You can also use hammer.js. There are both events - swipe your finger across the screen. In hammer.js you can get directions and distance. The tap event is also part of the new versions of jQuery - you do not need to enable jquery-mobile just for the tap event.

Hammer.js documentation

Hope this works for you.

+1
source

There is another plugin to handle all touch events. Please check

http://quojs.tapquo.com/

https://github.com/soyjavi/quojs

+1
source

Source: https://habr.com/ru/post/944425/


All Articles