2
\$\begingroup\$

I have a modal window that needs to be closed, obviously. I've created this piece of code that works okay. But is there a way to optimize it?

// close the modal window
$('.modal-close').click(function(e) {       
    $('#modal').hide();
    $('#modal-overlay').hide();

    e.preventDefault();
});

$(document).keydown(function(e) {
    if (e.keyCode == 27) { // if Esc key is pressed
        $('#modal').hide();
        $('#modal-overlay').hide();
    }

    if (e.keyCode == 9) { // cancel the Tab key
        return false;
    }
});
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

You can combine a couple of things: The close functionality can be function, and jQuery can operate on several elements at once:

function closeModal(event) { // passing in an event obj is optional
  $("#modal, #modal-overlay").hide();
  if(event) {
    event.preventDefault();
  }
}

$(".modal-close").click(closeModal);

$(document).keydown(function(event) {
  switch(event.keyCode) {
    case 27: // esc
      closeModal();
      break;
    case 9: // tab
      event.preventDefault();
      break;
    default: // everything else
      break;
  }
}

I've switched the keydown handler to use a switch statement, but that's not critically important. The point is just that since the keycode will be either one number or the other, there's no need for multiple ifs, and a switch is simple to extend if you need to handle more keycodes.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.