How to handle ESC keydown on javascript popup window

Viewed 97327

I have a javascript window.open popup, and I want the popup to close itself when the user presses the ESC key. I can't figure out how to hook the keydown event (and on what object?) so that I can catch the ESC key.

I'm using jQuery.

8 Answers

To handle both esc and enter key on dialog window.onkeydown = function(event) {

if(event.keyCode===27|| event.keyCode===13){
   window.close();
}
}

In case if any looking for angularjs popup solution here you go

*this is without using ui-bootstrap dependency(only recommended when there is no other way)

$scope.openModal = function(index){
    $scope.showpopup = true;
    event.stopPropagation();//cool part
};

$scope.closeModal = function(){
    $scope.cc.modal.showpopup = false;
};

window.onclick = function() {
  if ($scope.showpopup) {
      $scope.showpopup = false;
      // You should let angular know about the update that you have made, so that it can refresh the UI
      $scope.$apply();
  }
};

//escape key functionality playing with scope variable
document.onkeydown = function (event) {
  const key = event.key; // const {key} = event; in ES6+
  if (key === "Escape") {
    if ($scope.showpopup) {
        $scope.showpopup = false;
        // You should let angular know about the update that you have made, so that it can refresh the UI
        $scope.$apply();
    }
  }
};

References: above answers and http://blog.nkn.io/post/hiding-menu-when-clicking-outside---angularjs/

Related