David Callanan David Callanan - 3 months ago 25
jQuery Question

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 alternitave way.

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

Thanks, help greatly appreciated!!

Answer

.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>

Comments