javascriptjqueryhtmlonkeypress

ESC kep to close the pop up form


I found a code online which helps me close pop up dialog using ESC button. The code is as follows:

<script type="text/javascript">
 function ESCclose(evt) {
  if (evt.keyCode == 27) 
   window.close();
 }
</script>

onkeypress

<body onkeypress="ESCclose(event)">

I tried using onkeypress in form tag. Its not working as I am unable to close the dialog using ESC button. Any help?


Solution

  • The issue is because the keypress event does not trigger for non-printable characters (eg backspace or escape).

    To solve the problem, you could use keydown instead:

    function ESCclose(evt) {
      if (evt.keyCode == 27) {
        //window.close();
        console.log('close the window...')
      }
    }
    <body onkeydown="ESCclose(event)"></body>

    As you've tagged the question with jQuery, you could use that to better separate your HTML and JS code:

    $(document).on('keydown', function(e) {
      if (e.keyCode == 27)
        window.close();
    });
    

    Note that no on* event attribute is required on the body element with the above code.