Removing a jQuery event handler while inside the event handler

javascript, jquery, jquery-events

Solution

you can use jquery off() method. You also could put your keydown logic in to a separate function so you only can target that keydown action in your off method.

var mykeydownfunction= function(){
    console.log(event);

    var tag = event.target.tagName.toLowerCase();
    if(event.which = 27 && tag != 'input' && tag != 'textarea'){    //escape has been pressed
        _dismissModal(modal_id);
        $(this).off('keydown', mykeydownfunction);// $(this) is the document
    }
}  

 $(document).on('keydown', mykeydownfunction);

Problem

I have a `keydown` event handler that I attach to my document so I can watch the `keydown` event everywhere. However, after a condition is met, I want to be able to remove that and only that handler. How can I do this? This is my current handler: ``` $(document).keydown(function(event){ console.log(event); var tag = event.target.tagName.toLowerCase(); if(event.which = 27 && tag != 'input' && tag != 'textarea'){ //escape has been pressed _dismissModal(modal_id); } }); ``` I want to remove this `keydown` event handler after `_dismissModal` is called. How can I do this without removing all `keydown` event handlers?

Original source