David Callanan David Callanan - 7 months ago 47
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
but neither are working.


Do I need to do
.on("click", function...)
.bind("click", function...)
instead of
if using
. 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!!


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

  <input id="element" type="text">
<button id="elementOff">Unbind Keydown and attach Click</button>