1
$(document).keypress(function(e)
{
  alert(e.keyCode);
  if(e.keyCode==27)
  {
    hide_menu();
  }
});

I get the alert for all keys except the escape key and the success part of the if is never getting called. Why this happens?

Sarvap Praharanayuthan
  • 4,212
  • 7
  • 47
  • 72

2 Answers2

7

use $(document).keyup instead of $(document).keypress

the following code works fine:

$(document).keyup(function(e) 
{
  alert(e.keyCode);

  if(e.keyCode==27)
  {
      alert ("Esc key");
      hide_menu();
  }
});
asim-ishaq
  • 2,190
  • 5
  • 32
  • 55
1

You can change the keypress to keyup(better to use keyup) or keydown:

$(document).keyup(function(e){
    alert(e.keyCode);
    if(e.keyCode==27){
       hide_menu();
    }
});
Jai
  • 74,255
  • 12
  • 74
  • 103