Unable to preventDefault inside passive event listener due to target being treated as passive - Chrome

Muhammad Tauseef picture Muhammad Tauseef · Apr 1, 2019 · Viewed 7.2k times · Source

I used the following code and started to get the below mention error what is wrong with the code and what is the fix for it.

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

<script>
jQuery(window).scroll(function() {

  if (jQuery(this).scrollTop() > 400) {

    jQuery('.headerN').css("width", "100%");
    jQuery('.headerN').slideDown();
  } else {
    jQuery('.headerN').slideUp();
  }
});
</script>

Answer

chennighan picture chennighan · Apr 1, 2019

In JQuery, it's still an open issue: https://github.com/jquery/jquery/issues/2871

You can do this with vanilla js on an event:

el.addEventListener('someEvent', someFn, { passive: false });

this is how someone on the github thread mentioned above created a workaround they implemented:

jQuery.event.special.touchstart = {
    setup: function( _, ns, handle ){
        if ( ns.includes("noPreventDefault") ) {
            this.addEventListener("touchstart", handle, { passive: false });
        } else {
            this.addEventListener("touchstart", handle, { passive: true });
        }
    }
};