We use cookies to enhance your experience on the site
CodeWorlds

Advanced Event Handling Techniques

Specialized techniques for advanced use cases.

Touch Gesture Handling

1// Touch gesture handling for mobile devices
2class TouchGestureHandler {
3  constructor(element) {
4    this.element = element;
5    this.startX = 0;
6    this.startY = 0;
7    this.currentX = 0;
8    this.currentY = 0;
9    this.isTracking = false;
10
11    this.bindEvents();
12  }
13
14  bindEvents() {
15    this.element.addEventListener('touchstart', (e) => this.handleTouchStart(e));
16    this.element.addEventListener('touchmove', (e) => this.handleTouchMove(e));
17    this.element.addEventListener('touchend', (e) => this.handleTouchEnd(e));
18  }
19
20  handleTouchStart(e) {
21    this.isTracking = true;
22    this.startX = e.touches[0].clientX;
23    this.startY = e.touches[0].clientY;
24  }
25
26  handleTouchMove(e) {
27    if (!this.isTracking) return;
28
29    e.preventDefault();
30    this.currentX = e.touches[0].clientX;
31    this.currentY = e.touches[0].clientY;
32
33    const deltaX = this.currentX - this.startX;
34    const deltaY = this.currentY - this.startY;
35
36    // Emit custom event with gesture data
37    this.element.dispatchEvent(new CustomEvent('gesture', {
38      detail: { deltaX, deltaY, isActive: true }
39    }));
40  }
41
42  handleTouchEnd(e) {
43    if (!this.isTracking) return;
44
45    this.isTracking = false;
46    const deltaX = this.currentX - this.startX;
47    const deltaY = this.currentY - this.startY;
48
49    // Determine gesture type
50    if (Math.abs(deltaX) > Math.abs(deltaY)) {
51      // Horizontal gesture
52      if (deltaX > 50) {
53        this.element.dispatchEvent(new CustomEvent('swipeRight'));
54      } else if (deltaX < -50) {
55        this.element.dispatchEvent(new CustomEvent('swipeLeft'));
56      }
57    } else {
58      // Vertical gesture
59      if (deltaY > 50) {
60        this.element.dispatchEvent(new CustomEvent('swipeDown'));
61      } else if (deltaY < -50) {
62        this.element.dispatchEvent(new CustomEvent('swipeUp'));
63      }
64    }
65
66    this.element.dispatchEvent(new CustomEvent('gestureEnd', {
67      detail: { deltaX, deltaY }
68    }));
69  }
70}
Go to CodeWorlds