Close Modal Window with the Escape Key
February 10th 2011Allowing users to close modal windows and the like by using the escape key is an important feature to include. Fortunately, it is a tiny piece of code.
In this snippet you can see that I am referencing the keyCode 27. This is the keyCode generated when someone presses the escape key. For my purpose, I was fading out two elements (#overlay and .popup) and removing the close button (a.close) that had been generated when the modal window was opened.
$(document).keyup(function(e) {
if (e.keyCode == "27") {
$('#overlay , .popup').fadeOut(function() {
$('a.close').remove(); //fade them both out
});
}
});