Search code examples
javascriptjqueryeventsevent-handlingunbind

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?


Solution

  • 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);