jQuery: disable and enable touch with touchmove

Morteza picture Morteza · Jan 16, 2013 · Viewed 42.9k times · Source

I use this code to disable and enable touch:

jQuery(document).ready(function(){

 jQuery("body").on("touchmove", false);

 jQuery('button').click(function(){
     jQuery("body").on("touchmove", true);
 });

});

function work fine for disabling touch but after click on button touch cannot be enable.

whats wrong on code?

Answer

Denys Séguret picture Denys Séguret · Jan 16, 2013

What is wrong is simply that you don't pass the argument required by on. You should pass a function (the event handler) and not just a boolean.

The simplest way to unbind then rebind is to have a boolean somewhere and test it in your handler. For example :

myapp = {active: true}; // change this boolean
jQuery("body").on("touchmove", function(e) {
    if (myapp.active) { // change myapp.active
        // do things
    }
});

If you want to unbind definitively, instead of passing false to on, use off. Passing false is a non documented trick that might break on future versions.

The off documentation also contains an example of another way to bind/unbind a function on click :

function aClick() {
  $("div").show().fadeOut("slow");
}
$("#bind").click(function () {
  $("body").on("click", "#theone", aClick)
    .find("#theone").text("Can Click!");
});
$("#unbind").click(function () {
  $("body").off("click", "#theone", aClick)
    .find("#theone").text("Does nothing...");
});