//Use a bootstrap modal which gives you default behavior of closing the modal on escape key or click on outside the modal.
OR
Use bootbox which gives a callback on click of yes or no.
OR
Use keyup event as shown below to close the modal. Keyup event is triggered after Keydown event, hence it is more appropriate to use keyup event in this scenario.
$(document).on('keyup',function(event) {
if (event.keyCode == 27) {
modal.hide();
}
});
UPDATE: Complete working example html below for bootstrap modal show and hide on ESC keypress.
Note: Along with data-keyboard="true", tabindex=-1 attribute is important for the ESC keypress functionality.
<html>
<head>
<meta charset="utf-8">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function () {
$("#hereBtn").click(function (e) {
$("#alertModal").modal('show');
});
});
</script>
<title>Bootstrap modal</title>
</head>
<body>
<div>Click <button id="hereBtn" class="btn btn-success">HERE</button> to open Success modal</div>
<div id="alertModal" class="modal fade" role="dialog" data-keyboard="true" tabindex="-1">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 id="alertHeader"> SUCCESS!!</h4>
</div>
<div class="modal-body">
<div id="alertMessage" class="alert alert-success">Now hit ESC or click outside this modal to close this modal window</div>
</div>
</div>
</div>
</div>
</body>
</html>