Removing a jQuery event handler while inside the event handler

Use .off() to remove the event handler.

$(document).on("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);
        $(this).off("keydown");
    }
});

This has been answered already but using namespaces with removing events is really helpful and makes sure you don't cause any side effects.

// add click event with my.namespace as the namespace
$('element').on('click.my.namespace', function (e) {
    // do something
});

// remove my.namespace click event from element
$('element').off('click.my.namespace');

You can open up the dev console and look at the events of an element with

$._data($('element')[0], 'events');

Open up the Object and you will see a click array. Expand your event and you will see the namespace actually shows up as

namespace.my

and not

my.namespace

http://api.jquery.com/on/

Search for Event names and namespaces for more info.


When the condition is met, use .off()

$(document).off('keydown');

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