Search code examples
javascriptpreventdefaultthrottlingtouchmove

How to prevent default browser scrolling an touchmove combined with a throttled function


I need to trigger a function when a finger moves on a touch device. When you touchmove, the default browser scrolling is disabled with e.preventDefault(); See first section on JsFiddle.

In order to reduce the traffic, this function is only called every half second while you touchmove with _.throttle from the underscore library. However, browser scrolling is not disabled any more. See second section.

How can I disable browser scrolling on touch devices even if the called function is throttled?

Section 1

$('#test1').on("touchmove", function (ev) {
    var e = ev.originalEvent;
    e.preventDefault();
    $('#test1').text(e.targetTouches[0].pageX, e.targetTouches[0].pageY);
});

Section 2

$('#test2').on("touchmove", _.throttle(function (ev) {
  var e = ev.originalEvent;
  e.preventDefault();                      // browser still scrolling - why?
  $('#test2').text(e.targetTouches[0].pageX);
},500));

Solution

  • Remove the e.preventDefault() and add return false; to the end of the function. Example:

    $('#test1').on("touchmove", function (ev) {
        var e = ev.originalEvent;
        e.preventDefault();
        $('#test1').text(e.targetTouches[0].pageX, e.targetTouches[0].pageY);
    });
    
    
    $('#test2').on("touchmove", _.throttle(function (ev) {
      var e = ev.originalEvent;
      $('#test2').text(e.targetTouches[0].pageX);
      return false;
    },500));
    

    Working Fiddle