Help us understand the problem. What is going on with this article?

jQueryの .on でハマった話

More than 1 year has passed since last update.

スマホでスクロールを禁止する記述を追加した

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

すると以下の警告が表示される

[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. 
See https://www.chromestatus.com/features/5093566007214080
preventDefault @ jquery-1.11.2.min.js:3 (anonymous)

URLが表示されているので中を見てみると

AddEventListenerOptions defaults passive to false. 
With this change touchstart and touchmove listeners added to the document will default to passive:true 
(so that calls to preventDefault will be ignored)..

If the value is explicitly provided in the AddEventListenerOptions it will continue having the value specified by the page.

This is behind a flag starting in Chrome 54, and enabled by default in Chrome 56. 
See https://developers.google.com/web/updates/2017/01/scrolling-intervention

Chrome56以降はデフォルトで passive:true になっているからスクロールできないよって言ってますね
理由は知らないですが、 passive: false を渡してあげるように修正してみます

$(document).on('touchmove', function(e) {e.preventDefault();}, {passive: false});

すると新規に以下のエラー

TypeError: ((m.event.special[e.origType] || {}).handle || e.handler).apply is not a function

何について怒られているのか全くわからない件・・・エラーの意味ないでしょこれ

jQuery側のエラーなので、記述方法について調べてみます。今回使ってるのは .on ですね
公式リファレンスを見てみます(http://api.jquery.com/on/
.on(events[,selector][,data],handler) と書かれていて、これを見る限りhandlerの後ろに第三引数で passive: false を渡すのは無理っぽいですね。ナンテコッタ

解決

素のJSのAddEventListenerのリファレンスを見てみます(https://developer.mozilla.org/ja/docs/Web/API/EventTarget/addEventListener
target.addEventListener(type, listener[, options]); と書かれていますね!こちらは options としてオブジェクトが渡せそうです。記述方法を下記の様に変えてみます

document.addEventListener('touchmove', function(e) {e.preventDefault();}, {passive: false});

エラー無し。スクロール制御ができました。
jQueryじゃ本当に無理なのかな?一旦これで。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした