Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unbind a specific event handler

Code:

$('#Inputfield').keyup(function(e)         {             if(e.which == 13)             {                 functionXyz();             }             else             {                 functionZyx();             }     });     $(document).keyup(function(exit) {               if (exit.keyCode == 27) { functionZzy(); } }); 

Question: How to remove the keyup event handler of keyCode == 27 and keep the other $(document).keyup event handlers intact?

like image 988
MeProtozoan Avatar asked Oct 19 '10 21:10

MeProtozoan


People also ask

How do you unbind an event listener?

The removeEventListener() is an inbuilt function in JavaScript which removes an event handler from an element for a attached event. for example, if a button is disabled after one click you can use removeEventListener() to remove a click event listener.

How do I remove a specific event listener in jQuery?

To remove specific delegated event handlers, provide a selector argument. The selector string must exactly match the one passed to . on() when the event handler was attached. To remove all delegated events from an element without removing non-delegated events, use the special value "**" .

Which function is used to remove an existing event handler?

The removeEventListener() method removes an event handler from an element.


2 Answers

You have to use a named function so you can reference that specific handler when calling .unbind(), like this:

function keyUpFunc(e) {   if (e.keyCode == 27) { functionZzy(); } } $(document).keyup(keyUpFunc); 

Then later when unbinding:

$(document).unbind("keyup", keyUpFunc); 
like image 65
Nick Craver Avatar answered Sep 22 '22 21:09

Nick Craver


Your are attaching the event handlers to different elements, so you can safely remove the handler from the specific object (already mentioned I know).

For the sake of completeness, if you want to attach multiple handlers for the same event to the same object, you can use namespaced events:

$('#Inputfield').bind('keyup.keep', function(e){/*...*/}); $('#Inputfield').bind('keyup.notkeep', function(e){/*...*/});  $('#Inputfield').unbind('keyup.notkeep'); // or event  $('#Inputfield').unbind('.notkeep'); 

Since jQuery 1.7, the methods .on and .off are the preferred way to add and remove event handlers. For this purpose they behave exactly like .bind and .unbind and also work with namespaced events.

like image 25
Felix Kling Avatar answered Sep 24 '22 21:09

Felix Kling