Fergoso
Fergoso

Reputation: 1582

preventDefault() error in Chrome for mousewheel DOMMouseScroll

I am getting this preventDefault() error in chrome console. I came across this blog article and tried few like adding { passive: false } but no luck. How can I solve this?

I also read that using return false; instead is recommended. But I'm not sure if that's the solution in my case. So I am seeking your advise.

$(document).on('wheel mousewheel DOMMouseScroll', function(event) {
    event.preventDefault();
    if(delay) return;

    delay = true;
    setTimeout(function(){delay = false},200)
        //some code
    });
})();

chrome error

[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See...

Thank you!

Upvotes: 2

Views: 2472

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

Based on the information given in the error, going to the URL linked in said error, there is no obvious way to fix this with jQuery (could be, but I don't use jQuery, so I'm saying you can't) ... with regular javascript - you can, in the third argument, pass {passive:false} - which fixes this Chrome "feature"

document.addEventListener('wheel', fn, {passive: false});
document.addEventListener('mousewheel', fn, {passive: false});
document.addEventListener('DOMMouseScroll', fn, {passive: false});

function fn(event) {
    event.preventDefault();
    if(delay) return;

    delay = true;
    setTimeout(function(){delay = false},200)
        //some code
}

or if you want a more jQuery feel to your code, create a helper function

const addListeners = (tgt, list, fn, options) => list.split(' ').forEach(e => tgt.addEventListener(e, fn, options));

Then use it like

addListeners(document, 'wheel mousewheel DOMMouseScroll', function(event) {
    event.preventDefault();
    if(delay) return;

    delay = true;
    setTimeout(function(){delay = false},200)
        //some code
    }, {passive: false}
);

As mentioned in the comments, some OLD (very very old) browsers may not like this syntax ({passive:true|false})

So - you may want to feature detect the option - code from https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support

var passiveSupported = false;

try {
  var options = {
    get passive() { // This function will be called when the browser
                    //   attempts to access the passive property.
      passiveSupported = true;
    }
  };

  window.addEventListener("test", options, options);
  window.removeEventListener("test", options, options);
} catch(err) {
  passiveSupported = false;
}

before using it, so internet explorer doesn't have a little cry about it

Upvotes: 3

Related Questions