10

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

achecopar
  • 421
  • 1
  • 11
  • 20
David Callanan
  • 5,601
  • 7
  • 63
  • 105
  • I had a similar problem like yours in a project while back. I think I added the click handler within a function as a callback. That way the click functionality didn't work again unless I called it through a different function. – DustinRW Aug 05 '16 at 21:17
  • @DustinRW I don't understand what you mean? – David Callanan Aug 05 '16 at 21:25
  • What I mean is wrapping your function within another function. Example, you could wrap your function _above_ within another written function and create a set of conditionals. `var outerFunction = function() { if (condition met) { $("#element").keydown(function() { // do stuff! }); };` I'm just assuming you want your function to only be called once then stop or only run when certain criteria is met. Hope my idea is clearer. – DustinRW Aug 07 '16 at 20:20
  • The thing is that the code for the keydown is not mine, it is external js. I just simply want to remove the keydown event which was already bound. It is alright though, thanks for the help! I've gotten it to work now. – David Callanan Aug 08 '16 at 10:53

2 Answers2

7

.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>
Community
  • 1
  • 1
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
  • Wrote the wrong thing, I actually do have `keydown` event, sorry. – David Callanan Aug 06 '16 at 10:42
  • @DavidCallanan Answer and snippet updated. I hope this can solve your problem – gaetanoM Aug 06 '16 at 12:12
  • @DavidCallanan could you try wrapping your code in $( window ).load(function() { function? – gaetanoM Aug 06 '16 at 12:32
  • Still not working. I am doing it on a canvas. I tried using the selector "*" as well incase I got the wrong element. I will try a set timeout function for 2 seconds after the page loads just to see what happens. – David Callanan Aug 06 '16 at 12:38
  • Still no luck. Do you know if it is possible to check the events on an element? Maybe they are not using keydown (although I'm not sure how it would work then). Or do you think using canvas has got to do with the problem? – David Callanan Aug 06 '16 at 12:44
  • wait... is jQuery able to remove dom event listeners, because I think the js might add it with element.addEventListener? – David Callanan Aug 06 '16 at 12:47
  • @DavidCallanan No, iQuery add event and addEventListener are different from what I understood. But a test is required. – gaetanoM Aug 06 '16 at 12:54
  • @DavidCallanan Try to take a look to http://stackoverflow.com/questions/4386300/javascript-dom-how-to-remove-all-events-of-a-dom-object – gaetanoM Aug 06 '16 at 13:07
  • Ok, I found this `var new_element = old_element.cloneNode(true);` `old_element.parentNode.replaceChild(new_element, old_element);` but this doesn't seem to work with canvas. – David Callanan Aug 06 '16 at 13:15
  • It's fine I got it to work. Thanks a million for all the help. Very much appreciated. – David Callanan Aug 06 '16 at 13:59
2

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");
});
krankuba
  • 1,283
  • 1
  • 17
  • 20
  • According to http://api.jquery.com/off/, it isn't neccessarry to pass in the callback to remove it. Also I can't remember where I read it but it said that you cannot pass in an anonymous function as the callback paramater. This is also external code from my friend which may change in the future (and uses anonymous functions), so how would I do it in that situation? – David Callanan Aug 06 '16 at 09:43
  • yes, sure. i just made example to show how "on" and "off" behave in the same context. to disable it you can simply '("#element").off("click");'. I just tried using the external script and it is unbinding the event successfully, so let me update my answer :) – krankuba Aug 06 '16 at 11:27