Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Swipe events when interacting with elements on a page

I am building an iPad application which is essentially a series of slides.

When I've finished reading a slide I am able to swipe to the next slide *(using Zepto's swipe) which changes the window.location to the next slide. (the swipe event is bound to the window.body as it needs to work on the whole page)...

Here is the problem: some slides have interactive elements such as buttons, draggable items etc. The problem is that the swipe event is triggered when using some of these interactive elements.

Does anyone know of a way to prevent swipe from triggering in these instances? Perhaps settings a sensitivity etc?

I'm stumped...

Best wishes and many thanks!!

like image 391
Chris Avatar asked Oct 21 '22 16:10

Chris


1 Answers

The way Zepto manages touch events is it binds listeners to the touchstart, touchend, and touchmove events on document.body. It then performs calculations on what event to send and triggers an event on the element that received the touchstart event. This event then bubbles up through the DOM tree evoking the listeners of each element.

This gives us two ways of preventing swipe events:

First, you could do something like:

$('#my-child-element').bind('touchstart touchend touchup', function(event) {
    event.stopPropagation();
});

When your child element receives one a touch event, it will prevent it from propagating to parent elements, most importantly the body tag. This prevents the Zepto touch processor from doing anything, blocking swipe, tap, singleTap, longTap, and doubleTap events from occurring while operating in that element.

Because swipe events also bubble, you could also just prevent those specific events from bubbling to your element that listens to page change swipes:

$('#my-child-element').bind('swipeLeft swipeRight', function(event) {
    event.stopPropagation();
});

This will allow you to still receive the Zepto generated events inside your child element but not outside. Zepto tap events will also still work for all elements within your child.

Fiddle here: http://jsfiddle.net/bnickel/dUuUd/

like image 147
Brian Nickel Avatar answered Oct 24 '22 11:10

Brian Nickel