سؤال

$(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?

هل كانت مفيدة؟

المحلول

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();
  }
});

نصائح أخرى

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();
    }
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top