jQuery multiple events execute same function refactoring I am working a project which uses a function to show a modal dialog. The dialog can be hidden by calling the hideModal() function. This function is triggered by:


Pressing the ESC key
Clicking on the modal background
Clicking on the close button


My current code is:

 $("#modal").click(function() {
    hideModal();
});

$("#modal-object-container &gt; a").click(function(e) {
    hideModal();
    e.preventDefault();
});

$(document).keydown(function (e) {

    if (e.keyCode == '27') {
        hideModal();
    }

});


I have the feeling there should be a faster way to bind all these events at once.
Your code isn't all that bad. However because you are binding key events on the document, you need to allow room, for other key events to be bound, for other tasks, so your code doesn't interfere with other ESC functions.

The concept is that you bind on click, and unbind upon hiding your modal. This way the key events are only applicable when your code is run.

// save your doc once, it's faster
var doc = $(document);
    // bind a function, which you can unbind later, so esc can be used in other cases as well, without triggering your function
    doc.bind('keydown', _processKey);

// on click binding for as many elements as you like. 
// The preventDefault shouldn't influence other elements in this case.
$("#modal, #modal-object-container &gt; a").click(function(ev) {
    ev.preventDefault();
    hideModal();
});

// when you hide your modal, you unbind the event, so the document is free for other events and functions
function hideModal() {
    doc.unbind('keydown', _processKey);
}

// have a 'private' function to do what you want. This way you can unbind it anytime you like
function _processKey(ev) {
    if (ev.keyCode == '27') {
        hideModal();
    }
}