Javascript stop scrolling on touchmove after scrolling has already started
Asked Answered
P

1

6

I have a simple example where a user starts to scroll on a touch screen, and then after one second, I want to disable scrolling. I thought event.preventDefault() would stop the scrolling but it doesn't seem to work after scrolling has already started

Here is an example: https://jsfiddle.net/7s5m8c6L/30/

let allowScroll=true;

function TS(e){//touchstart handler
  setTimeout(function(){
    allowScroll=false;
  },1000)
}

function TM(e){//touchmove handler
  if(!allowScroll){
    e.preventDefault();
  }
}

In this example, you can start scrolling, and after a second, I want the scrolling to stop, but it does not. I know there are ways that I can get this to work with CSS (adding overflow:hidden), but I would particularly like to know why preventDefault doesn't work.

Pruett answered 31/5, 2021 at 5:1 Comment(0)
J
1

If you are using chrome, there is a hint in the console:

[Intervention] Ignored attempt to cancel a touchmove event with cancelable=false, for example because scrolling is in progress and cannot be interrupted.

The problem is exactly that Event.cancelable. Unfortunately for you this property is read-only and it is not safe to call preventDefault for a not cancelable event. If you print e.cancelable in the TM function you can observe that throughout the scrolling e.cancelable is false.

Joshua answered 2/6, 2021 at 7:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.