Is it possible to recognize diagonal swipe using Hammer.js?
I have gone through their documentation but didn't find anything saying about diagonal swiping or pan etc...
An object with a lot of info about the gesture is passed to every Hammer.js event callback (as described here in the API docs).
The eventObject.angle
property is what you are looking for. Its values are between -180 and 180 (0 means RIGHT, -90 means UP, 90 means DOWN, 180 means LEFT).
So here's how you can recognize diagonal swipes:
var hammertime = new Hammer(domElement);
hammertime.get("swipe").set({ direction: Hammer.DIRECTION_ALL });
hammertime.on("swipe", function(eventObject) {
if(eventObject.angle < -90) {
//UP-LEFT SWIPE...
} else if(eventObject.angle < 0) {
//UP-RIGHT SWIPE...
} else if(eventObject.angle < 90) {
//DOWN-RIGHT SWIPE...
} else {
//DOWN-LEFT SWIPE...
}
});
For those who want an 8 way swipe (up, down, left, right, up-left, down-left, up-right, down--right) option using HammerJS. it's worth looking into using the angle in a range of values. The left option is the only clever one... since it's an OR statement rather than an AND statement.
var hammertime = new Hammer(domElement);
hammertime.get("swipe").set({ direction: Hammer.DIRECTION_ALL });
hammertime.on("swipe", function(e) {
let jResult = '';
switch(true) {
// LEFT
case (e.angle < -157.5 || e.angle > 157.5):
jResult = 'left';
break;
// RIGHT
case (e.angle > -22.5 && e.angle < 22.5):
jResult = 'right';
break;
// UP
case (e.angle < -67.5 && e.angle > -112.5):
jResult = 'up';
break;
// Down
case (e.angle > 67.5 && e.angle < 112.5):
jResult = 'down';
break;
// LEFT-Up
case (e.angle < -112.5 && e.angle > -157.5):
jResult = 'left-Up';
break;
// LEFT-Down
case (e.angle > 112.5 && e.angle < 157.5):
jResult = 'left-Down';
break;
// RIGHT-Up
case (-22.5 > e.angle && e.angle > -67.5):
jResult = 'right-Up';
break;
// RIGHT-Down
case (e.angle > 22.5 && e.angle < 67.5):
jResult = 'right-Down';
break;
default:
// code block
jResult = 'unknown'; // UNKNOWN - what happened?
}
console.log('--00--> Swipe: ' + e.direction + ' -- Dir is: ' + jResult);
this.lastSwipe = jResult;
});
Output is shown to console... your milage may vary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With