1

I have a script like this:

$(document).ready(function(){

window.addEventListener('mousewheel', function(e){
    e.preventDefault();
},{passive:false});

});

So now I need to make another function when on click of a button to override the above script and to "return" the default behavior.

I tested this:

$('#button').on('click', function(){
    window.off('mousewheel');
});

And it's not working.

EDIT 2:

Just tested this and still not working:

$('#button').on('click', function(){
    window.removeEventListener('mousewheel', function(e){
        return true;
    }, true);
});
Emmanuel-Ab
  • 181
  • 13
  • 1
    Does this answer your question? [Best way to remove an event handler in jQuery?](https://stackoverflow.com/questions/209029/best-way-to-remove-an-event-handler-in-jquery) – Justinas Aug 10 '20 at 09:32
  • @Justinas No I just tested this and does not work, the prevent default is still doing its thing. – Emmanuel-Ab Aug 10 '20 at 09:33
  • Did you try just to remove the handler? – Claus Bönnhoff Aug 10 '20 at 09:45
  • @ClausBönnhoff Hmm, how can I achieve this – Emmanuel-Ab Aug 10 '20 at 09:47
  • You cannot remove anonymous event listeners with `removeEventListener`. Have a look at this answer https://stackoverflow.com/a/32809957/443523 – Mark Baijens Aug 10 '20 at 09:57
  • As @ClausBönnhoff said you can remove the listener this way, just by passing the addEventListener a function reference, that you will use later to remove it. `var myEventListner = function (e) ...;` `window.addEventListener('mousewheel', myEventListner);` and later : `window.removeEventListener("mousewheel", myEventListner);` – Tmb Aug 10 '20 at 09:58
  • @tmb Just tested it! Works perfectly!! Thank you! – Emmanuel-Ab Aug 10 '20 at 10:03

1 Answers1

1

Works Fine!

$(document).ready(function() {

  function foo(e) {
    console.log("mousewheel");
    e.preventDefault();
  }

  window.addEventListener('mousewheel', foo, true);

  $('#button').on('click', function() {
    console.log("click");
    window.removeEventListener('mousewheel', foo, true);

  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button">Button</button>
tushar wason
  • 174
  • 5