Skip to main content

Working with Gestures

1. Creating Custom Gestures

Property Description Values Notes
gestureName Name of the gesture to be created string Must be unique within the app
threshold Minimum distance in pixels for gesture recognition number Default: 10px
direction Direction of the gesture (horizontal or vertical) 'horizontal' | 'vertical' Default: 'horizontal'
requirements Additional conditions to trigger the gesture Array<string> Can include 'swipe', 'pinch', etc.

Example: Creating a Custom Swipe Gesture

import { Gesture, createGesture } from '@ionic/core';

const swipeGesture = createGesture({
  gestureName: 'custom-swipe',
  threshold: 15,
  direction: 'horizontal',
  requirements: ['swipe']
});

swipeGesture.on('swipe', (event) => {
  console.log('Custom swipe detected:', event);
});

2. Handling Gesture Events

Event Description Properties
ionGesture Base gesture event gesture, event
ionDrag Drag gesture event deltaX, deltaY, velocityX, velocityY
ionSwipe Swipe gesture event direction, velocity
ionPress Press gesture event time, isPrimary

Example: Handling Drag Events

import { IonContent } from '@ionic/angular';

@Component({
  selector: 'app-gesture-demo',
  template: '<ion-content (ionDrag)="onDrag($event)"></ion-content>'
})
export class GestureDemoComponent {
  onDrag(event: any) {
    console.log('Drag delta X:', event.deltaX);
    console.log('Drag delta Y:', event.deltaY);
  }
}

Example: Handling Swipe Events

import { IonContent } from '@ionic/angular';

@Component({
  selector: 'app-swipe-demo',
  template: '<ion-content (ionSwipe)="onSwipe($event)"></ion-content>'
})
export class SwipeDemoComponent {
  onSwipe(event: any) {
    console.log('Swipe direction:', event.direction);
    console.log('Swipe velocity:', event.velocity);
  }
}

3. Detecting Swipe Gestures

Property Description Values
swipeThreshold Minimum distance in pixels required to recognize a swipe 50
direction Direction of swipe to detect 'left', 'right', 'up', 'down'

Example: Detecting Swipe Left

const swipeGesture = new Ionic.Gesture({
  el: document.getElementById('swipe-area'),
  threshold: 50,
  direction: 'left'
});

swipeGesture.on('swipe', (event) => {
  console.log('Swipe left detected');
});
Note: The swipeThreshold can be adjusted based on user interaction needs.
Warning: Ensure that swipe gestures do not conflict with other touch interactions.

4. Implementing Pan Gesture

Property Description Values
direction Sets the direction of the pan gesture 'x', 'y', 'xy'
threshold Minimum distance in pixels before gesture is recognized 0 to 100
pointers Number of pointers to recognize 1, 2

Example: Pan Gesture Configuration

import { PanGesture } from '@ionic/angular';

const panGesture = new PanGesture({
  direction: 'x',
  threshold: 10,
  pointers: 1
});

Example: Pan Gesture Handler

const handlePan = (ev: any) => {
  console.log('Pan delta X:', ev.deltaX);
  console.log('Pan delta Y:', ev.deltaY);
};

5. Using Tap Gesture

Property Description Default Notes
tap Event triggered when a tap gesture is recognized null Used to handle single tap interactions

Example: Handling Tap Gesture

import { Component } from '@angular/core';
import { Gesture, createGesture } from '@ionic/angular';

@Component({
  selector: 'app-tap-example',
  template: &#x27;<ion-content><div (tap)="handleTap()">Tap me</div></ion-content>&#x27;
})
export class TapExampleComponent {
  handleTap() {
    console.log("Single tap detected");
  }
}
Note: The tap gesture is optimized for mobile touch devices and can be combined with other gestures for complex interactions.

6. Configuring Gesture Threshold

Property Description Default Value Notes
threshold Minimum distance (in pixels) the user must move before a gesture is recognized. 10 Adjusts sensitivity of gesture detection.
maxPointers Maximum number of simultaneous pointers (fingers) to consider for gesture recognition. 1 Useful for multi-touch gestures like pinch-to-zoom.

Example: Adjusting Gesture Threshold

const gestureConfig = {
  threshold: 20,
  maxPointers: 2
};

// Apply to a component or element
const element = document.querySelector('.my-element');
element.gestureConfig = gestureConfig;

7. Preventing Default Behavior

Method Description Usage
preventDefault() Stops the default action of an event from occurring event.preventDefault();
stopPropagation() Prevents the event from bubbling up the DOM tree event.stopPropagation();

Example: Preventing Default Behavior in Ionic

handleSwipe(event: any) {
  event.preventDefault();
  event.stopPropagation();
  // Custom swipe logic here
}
Note: Using preventDefault() is essential for disabling native browser gestures like scrolling or zooming in touch environments.

8. Combining Multiple Gestures

Combining multiple gestures in Ionic allows for more complex user interactions. You can chain gesture recognizers to handle various touch and pointer events simultaneously.

Gesture Description Usage Notes
pan Recognizes horizontal or vertical panning gestures pan Can be combined with other gestures for complex interactions
pinch Recognizes scaling gestures using two fingers pinch Often used for zooming in/out of elements
rotate Recognizes rotation gestures using two fingers rotate Useful for rotating UI components or images
tap Recognizes single tap gestures tap Can be used to trigger actions on elements

Example: Combining Pan and Tap Gestures

import { Gesture, createGesture } from '@ionic/core';

const gesture = createGesture({
  el: document.getElementById('myElement'),
  gestureName: 'panTap',
  onEnd: (ev) => {
    console.log('Gesture ended', ev);
  }
});

gesture.enable();

Example: Using Pinch and Rotate Together

import { Gesture, createGesture } from '@ionic/core';

const pinchRotate = createGesture({
  el: document.getElementById('zoomableElement'),
  gestureName: 'pinchRotate',
  onEnd: (ev) => {
    if (ev.type === 'pinch') {
      console.log('Pinched with scale: ', ev.scale);
    } else if (ev.type === 'rotate') {
      console.log('Rotated by: ', ev.rotation);
    }
  }
});

pinchRotate.enable();
Note: When combining gestures, ensure that they do not conflict with each other. For example, a pan gesture might interfere with a swipe gesture if both are enabled on the same element.

9. Disabling Gestures

Example: Disable All Gestures on a Component

<ion-button disabled-gestures="true">No Gestures</ion-button>
Property Values Description
disabled-gestures true | false Disables all gesture handlers on the component. Defaults to false.
Note: This property is useful for components that should not respond to swipe, tap, or pan gestures, such as buttons in a carousel or static content areas.

10. Using Gesture Animations

Property Description Values Notes
gesture Gesture type to use for animation pan, tap, press Used to define the type of gesture that triggers the animation
duration Duration of the animation in milliseconds number Defaults to 300ms if not specified
easing Easing function for the animation ease-in-out, linear, ease-in, ease-out Controls the speed curve of the animation

Example: Using Gesture Animation

import { Gesture, createGesture } from '@ionic/core';

const gesture = createGesture({
  el: document.querySelector('.my-element'),
  gestureName: 'pan',
  threshold: 10,
  onEnd: (ev) => {
    console.log('Gesture ended:', ev);
  }
});

gesture.enable();
Note: The gesture animation requires the element to have a CSS transition property defined for smooth animation.
Warning: Ensure that the gesture element is properly initialized and enabled to avoid unexpected behavior.

Was this article helpful?