Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop jQuery Mobile swipe event double bubbling

I have jQuery Mobile on iPad Safari and for some reason touch swipe events are firing twice.

People have reported the same problem over the past year as recently as this week but I cannot find an explanation for how to fix the double event without modifying jQuery Mobile and I do not want to do that. Thread on jQuery forums

The follwoing element bindings for the swipe handler all have the same incorrect double-event result where the alert is called twice for every one swipe.

How should jQuery Mobile touch events be bound in order to avoid double bubbling?

// Test 1: Binding directly to document with delegate()
$(document).delegate(document, 'swipeleft swiperight', function (event) {
    alert('You just ' + event.type + 'ed!');
});


// Test 2: Binding to document with on() handler recommended as of 1.7 with and without preventDefault
$(document).on('swipeleft',function(event, data){
    event.preventDefault();
    alert('You just ' + event.type + 'ed!');
});


// Test 3: Binding to body with on() with and without event.stopPropagation 
$('body').on('swipeleft',function(event, data){
   event.stopPropagation();
   alert('You just ' + event.type + 'ed!');
});


// Test 4: Binding to div by class
$('.container').on('swipeleft',function(event, data){
   event.stopPropagation();
   alert('You just ' + event.type + 'ed!');
});
like image 410
Dylan Valade Avatar asked Mar 19 '12 01:03

Dylan Valade


2 Answers

event.stopImmediatePropagation() was the trick, which is different from stopPropagation(). Ensuring the jQuery on() method is called in document.ready seems to help. I was able to use any element selector to bind the events including using the swipeup and swipe down from here

$(document).ready(function(){    
    $(document).on('swipeleft swiperight swipedown swipeup',function(event, data){
        event.stopImmediatePropagation();
        console.log('(document).Stop prop: You just ' + event.type + 'ed!');
    });
});
like image 132
Dylan Valade Avatar answered Oct 11 '22 21:10

Dylan Valade


Well, had the same problem with swipe event been called twice. The workaround is to bind the event this way:

$(document).on('swipeleft', '#div_id',  function(event){
    //console.log("swipleft"+event);
    // code 
});
like image 27
Rodrigo Dias Avatar answered Oct 11 '22 21:10

Rodrigo Dias