2

I have been trying to stop scrolling in touch devices and I used the touchmove event for that as:

$('body').on('touchmove.sidebar', function(e){                        
  e.preventDefault();
});

In Chrome console I see the warning:

Unable to preventDefault inside passive event listener due to target being treated as passive. See https://www.chromestatus.com/features/5093566007214080

On github it has been suggested to use touch-action: none instead of preventDefault(). So my question is:

Should I use both preventDefault() and touch-action: none or only the later? Would the later work for firefox and other touch browsers?

Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84
user31782
  • 7,087
  • 14
  • 68
  • 143

1 Answers1

2

The reason you are seeing the warning in Chrome is because, by default from Chrome Version 54, to enhance scroll performance, it assumes that no preventDefault() will be called for document level.

I haven't used jQuery much so, in simple js:

body.addEventListener("touchmove", function(e){}, passive:false);

Check this answer out

Note-1: Make sure that you are providing another way to scroll through your page if it needs scrolling.

Note-2: Try to add the event handler to specific elements in your HTML page rather than the HTML-body if possible.

Now to answer your question:

You do not need both, either one is sufficient. Decide based on your requirement.

  1. Check caniuse and if you are happy with the browser support touch-action has, go for it.

  2. If you are not satisfied with the support it provides, use the preventDefault() method.

Note: preventDefault() method will be applied only when the specified event is occurring, and by specifying the style touch-action:none, touchEvents for that respective element won't be fired at all, as long as this style is applied.

Do check this link for more understanding: https://www.html5rocks.com/en/mobile/touchandmouse/

Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84
123survesh
  • 561
  • 3
  • 13
  • 1
    You have an error there, instead of `passive:false` you should have `{passive:false}`. This code helped me to prevent default touch events on desktop chrome: `document.addEventListener("touchstart", function(e){e.preventDefault();},{passive: false});` – Fanky Feb 17 '19 at 22:23