pjk_ok
pjk_ok

Reputation: 947

Change Mouse Wheel event on Window Object to {passive: false} - Javascript

With the latest update to Chrome[73], they have changed how the passive event listener works with the mouse wheel on the window object. Basically this has broken a number of smooth-scroll plugins which take away the default 'judder' of the traditional mouse wheel when scrolling in Chrome.

The change on the chrome platform status is here.

https://www.chromestatus.com/features#browsers.chrome.owners%3A%20sahel%40chromium.org

...and on this page it takes you to page where it says that the default is now the equivalent to this:

`window.addEventListener("wheel", func, {passive: true} );`

So I'm guessing I need to write a function that changes it to:

`window.addEventListener("wheel", func, {passive: false} );`

https://github.com/sahel-sh/Document-level-passive-wheel-event-listeners/blob/master/Explainer.md

I'd like to do this as a stand alone function instead of going through all of the code of the plugin I use trying to work out how and where to do this.

Would anyone know how to write a standalone function that would do this?

Nothing I do seems to work. How do I solve this problem?

Upvotes: 1

Views: 2655

Answers (1)

rinick
rinick

Reputation: 11

try this

const EVENTS_TO_MODIFY = ['touchstart', 'touchmove', 'touchend', 'touchcancel', 'wheel'];

const originalAddEventListener = document.addEventListener.bind();
document.addEventListener = (type, listener, options, wantsUntrusted) => {
  let modOptions = options;
  if (EVENTS_TO_MODIFY.includes(type)) {
    if (typeof options === 'boolean') {
      modOptions = {
        capture: options,
        passive: false,
      };
    } else if (typeof options === 'object') {
      modOptions = {
        ...options,
        passive: false,
      };
    }
  }

  return originalAddEventListener(type, listener, modOptions, wantsUntrusted);
};

const originalRemoveEventListener = document.removeEventListener.bind();
document.removeEventListener = (type, listener, options) => {
  let modOptions = options;
  if (EVENTS_TO_MODIFY.includes(type)) {
    if (typeof options === 'boolean') {
      modOptions = {
        capture: options,
        passive: false,
      };
    } else if (typeof options === 'object') {
      modOptions = {
        ...options,
        passive: false,
      };
    }
  }
  return originalRemoveEventListener(type, listener, modOptions);
};

Upvotes: 1

Related Questions