How to Add Up/Down Swipe Functionality to Sencha Touch

Whilst working with the Sencha Touch mobile JS framework, I was disappointed to find that it only handles left/right swiping.

The application I’m working on requires swiping up/down/left/right to navigate, so I needed to add this functionality to the code. It was simple enough to hack the Sencha Touch JS file, but this would have prevented me from upgrading as future versions are released.

Extending Sencha Touch wasn’t as straightforward as it seemed, I tried without success to use Ext.extend() to add a new gesture.

In the end I simply overrode the default ‘swipe’ gesture in my custom JS file:

Ext.gesture.SwipeVert = Ext.extend(Ext.gesture.Gesture, {

	/* Custom Swipe Gesture Handler which adds 'Up' and 'Down' to the default 'Left' and 'Right' */
    listenForEnd: false,

    swipeThreshold: 35,
    swipeTime: 1000,

    onTouchStart : function(e, touch) {
        this.startTime = e.timeStamp;
        this.startX = touch.pageX;
        this.startY = touch.pageY;
        this.lock('scroll', 'scrollstart', 'scrollend');
    },

    onTouchMove : function(e, touch) {

        var deltaY = touch.pageY - this.startY,
            deltaX = touch.pageX - this.startX,
            absDeltaY = Math.abs(deltaY),
            absDeltaX = Math.abs(deltaX),
            deltaTime = e.timeStamp - this.startTime;

        // If the swipeTime is over, we are not gonna check for it again
        if (deltaTime > this.swipeTime) {
            this.unlock('scroll', 'scrollstart', 'scrollend');
            this.stop();
        }
        else if (absDeltaX > this.swipeThreshold && absDeltaX > absDeltaY) {
           // If this is a swipe, a scroll is not possible anymore
           this.fire('swipe', e, {
               direction: (deltaX < 0) ? 'left' : 'right',
               distance: absDeltaX,
               deltaTime: deltaTime,
               deltaX: deltaX
           });

           this.stop();
        }
		/* Custom Code Goes Here */
        else if (absDeltaY > this.swipeThreshold && absDeltaY > absDeltaX) {
           // Handle Vertical
           this.fire('swipe', e, {
               direction: (deltaY < 0) ? 'up' : 'down',
               distance: absDeltaY,
               deltaTime: deltaTime,
               deltaY: deltaY
           });

           this.stop();
        }
        /* End Custom Code */
    }
});

Ext.regGesture('swipe', Ext.gesture.SwipeVert);

It works flawlessly!

You can leave a response, or trackback from your own site.

Leave a Reply

Powered by WordPress