Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove keydown event from jquery element not working

I have keydown event on element.

$("#element").keydown(function() {
     // do stuff!
});

Now I want to remove it.

I tried unbind and off but neither are working.

$("#element").unbind("click");
$("#element").off("click");

Do I need to do .on("click", function...) or .bind("click", function...) instead of .click if using unbind or off. If so, this is not my code and I am not allowed to modify it, so I need an alternative way.

Is there any other way than 'unbind' or 'off' that actually works?

Thanks, help greatly appreciated!!

like image 578
David Callanan Avatar asked Aug 05 '16 20:08

David Callanan


2 Answers

.off( events [, selector ] [, handler ] ): version added: 1.7

.unbind( eventType [, handler ] ): version added: 1.0

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on(), see .off(). To attach an event that runs only once and then removes itself, see .one()

So, I suggest to pay attention to the jQuery version, because bind/unbind are not used so much more.

In the following snippet you can see the .off() works fine:

$( window ).load(function() {
  $("#element").keydown(function(e) {
    console.log('keydown event');
  });
  $("#elementOff").click(function() {
    // unbind keydown
    $("#element").off('keydown');
    
    // attach click
    $("#element").off('click').click(function(e) {
      console.log('click event');
    });
  });
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<form>
  <input id="element" type="text">
</form>
<button id="elementOff">Unbind Keydown and attach Click</button>
like image 51
gaetanoM Avatar answered Oct 27 '22 03:10

gaetanoM


As the .click() method is just a shorthand for .on( "click", handler ), detaching is possible using .off( "click" ):

$("#element").off("click", function(){
    $("#element").hide(); //not working
});

$("#element2").on("click", function() {
    $("#element2").hide(); //working
});

So if you have a .keydown( handler ), it is a shortcut for .on( "keydown", handler ) in the first and second variations, and .trigger( "keydown" ) in the third.

The arguments provided must match for the event handler to be removed.

If you do not want to touch the existing script or it may be changed i recommend you simply include an external .js script to the html page to unbound the events:

<script src="your_external_script.js"></script>

with similar content:

$(document).ready(function(){
    $("#element2").unbind("click");
});
like image 28
krankuba Avatar answered Oct 27 '22 01:10

krankuba