ebakunin
ebakunin

Reputation: 3791

Prevent accidental scrolling with swipe in jQuery Mobile

I am using jQuery Mobile. When swiping left or right the user can accidentally scroll the page, frequently "bouncing" the page off the top of the window. I want to suppress page scrolling during the left or right swipe event. I've tried:

$('#foo').on('swipeleft swiperight', function (ev) {
    $.event.special.swipe.scrollSupressionThreshold = 100;
    ...
});

but this does not prevent the behavior. I also tried adding position: fixed during the swipe event for both the html and body DOMs. Neither works because they alter the flow of the page. How should I approach this problem? Thanks.

Upvotes: 3

Views: 1445

Answers (2)

Nagama Inamdar
Nagama Inamdar

Reputation: 2857

With Beta 2 they have released some additional swipe functionality

Configurable swipe event thresholds added

There were a number of hard-coded constants in the jquery.mobile.event.js swipe code. For developers who need to tweak those constants to allow a greater vertical displacement and still register a swipe, this new feature allows them to be adjusted. Thanks to mlitwin for contributing this.

  • scrollSupressionThreshold (default: 10px) – More than this horizontal displacement, and we will suppress scrolling
  • durationThreshold (default: 1000ms) – More time than this, and it isn’t a swipe
  • horizontalDistanceThreshold (default: 30px) – Swipe horizontal displacement must be more than this.
  • verticalDistanceThreshold (default: 75px) – Swipe vertical displacement must be less than this.

Upvotes: 1

digitaldonkey
digitaldonkey

Reputation: 2465

You can use a debounce function like the one I took from here

// Minified: only 160 bytes!
function debounce(a,b,c){var d;return function(){var e=this,f=arguments;clearTimeout(d),d=setTimeout(function(){d=null,c||a.apply(e,f)},b),c&&!d&&a.apply(e,f)}}

var myDebouncedFn = debounce(function() {
 // All the taxing stuff you do
}, 250);
window.addEventListener('swipe', myDebouncedFn);

But you should better read into jQuery Mobile Documentation, because this is built in:

$.event.special.swipe.scrollSupressionThreshold (default: 10px) – More than this horizontal displacement, and we will suppress scrolling.
$.event.special.swipe.durationThreshold (default: 1000ms) – More time than this, and it isn't a swipe.
$.event.special.swipe.horizontalDistanceThreshold (default: 30px) – Swipe horizontal displacement must be more than this.
$.event.special.swipe.verticalDistanceThreshold (default: 75px) – Swipe vertical displacement must be less than this.

Upvotes: 1

Related Questions