Swiping, user gestures?

Hey there,

Is there any way to recognize user gestures on the device, such as a swipe gesture? It would be nice to be able to use those as events, for example, switching a form based on a swipe-left, swipe-right, etc.

2 Likes

Yes, you can definitely do it.

You can refer to this for adding touch event listeners and tweak it to accommodate left and right swipes instead of a pull to refresh.

Untested but something like this:


content_panel = anvil.js.get_dom_node(self.content_panel)
content_panel.addEventListener('touchstart', self.on_touch_start)
content_panel.addEventListener('touchmove', self.on_touch_move)
content_panel.addEventListener('touchend', self.on_touch_end)

self.touch_start_x = None
self.touch_end_x = None

def on_touch_start(self, event):
    self.touch_start_x = event.touches[0].clientX

def on_touch_move(self, event):
    self.touch_end_x = event.touches[0].clientX

def on_touch_end(self, event):
    if self.touch_start_x is not None and self.touch_end_x is not None:
        swipe_distance = self.touch_end_x - self.touch_start_x
        if swipe_distance > 50:
            self.swipe_right()
        elif swipe_distance < -50:
            self.swipe_left()
    self.touch_start_x = None
    self.touch_end_x = None

def swipe_right(self):
    # Handle swipe right event
    print("Swiped right")

def swipe_left(self):
    # Handle swipe left event
    print("Swiped left")

4 Likes