TinyGesture.js
Very small gesture recognizer for JavaScript. Swipe, pan, tap, doubletap, longpress, pinch, and rotate.
Installation
npm install --save tinygesture
- If you're upgrading from v2, the
diagonalLimit
option has changed meaning and there are new events for pinch and rotate. Also TS now exports ES2020 instead of ES6. - If you're upgrading from v1, the location of the file has changed. It's now in a "dist" folder, hence the major version change.
Usage
Constructor and Options
import TinyGesture from 'tinygesture';
const options = {
threshold: (type, self) =>
Math.max(
25,
Math.floor(
0.15 *
(type === 'x'
? window.innerWidth || document.body.clientWidth
: window.innerHeight || document.body.clientHeight),
),
),
velocityThreshold: 10,
disregardVelocityThreshold: (type, self) =>
Math.floor(0.5 * (type === 'x' ? self.element.clientWidth : self.element.clientHeight)),
pressThreshold: 8,
diagonalSwipes: false,
diagonalLimit: 15,
mouseSupport: true,
};
const target = document.getElementById('target');
const gesture = new TinyGesture(target, options);
Listening to Gesture Events
gesture.on('panstart', (event) => {
event;
gesture.touchStartX;
gesture.touchStartY;
});
gesture.on('panmove', (event) => {
gesture.touchMoveX;
gesture.touchMoveY;
gesture.velocityX;
gesture.velocityY;
gesture.swipingHorizontal;
gesture.swipingVertical;
gesture.swipingDirection;
if (gesture.swipingDirection === 'horizontal' && gesture.touchMoveX < 0) {
alert('You are currently swiping left.');
}
});
gesture.on('panend', (event) => {
gesture.touchEndX;
gesture.touchEndY;
});
gesture.on('swiperight', (event) => {
gesture.swipedHorizontal;
gesture.swipedVertical;
});
gesture.on('swipeleft', (event) => {
gesture.swipedHorizontal;
gesture.swipedVertical;
});
gesture.on('swipeup', (event) => {
gesture.swipedHorizontal;
gesture.swipedVertical;
});
gesture.on('swipedown', (event) => {
gesture.swipedHorizontal;
gesture.swipedVertical;
});
gesture.on('tap', (event) => {
});
gesture.on('doubletap', (event) => {
});
gesture.on('longpress', (event) => {
});
gesture.on('pinch', (event) => {
gesture.scale;
});
gesture.on('pinchend', (event) => {
});
gesture.on('rotate', (event) => {
gesture.rotation;
});
gesture.on('rotateend', (event) => {
});
Long Press without Tap
If you want to listen for both long press and tap, and distinguish between them, this is how to do it.
let pressed = false;
gesture.on('tap', () => {
if (pressed) {
return;
}
});
gesture.on('longpress', () => {
pressed = true;
});
gesture.on('panend', () => {
if (pressed) {
setTimeout(() => {
pressed = false;
}, 0);
}
});
Un-listening to Gesture Events
const callback = (event) => {};
const listener = gesture.on('tap', callback);
listener.cancel();
gesture.off('tap', callback);
Firing Events
gesture.fire('tap', eventObj);
Destruction
gesture.destroy();
Credits
A lot of the initial ideas and code came from:
https://gist.github.com/SleepWalker/da5636b1abcbaff48c4d
and
https://github.com/uxitten/xwiper