简体   繁体   中英

Execute JavaScript on Key Press

I am trying to add a script to my website that is only executed on key press, using JavaScript to handle the event. They specific key to be pressed is the one located below the "esc" key; the "`" key. I have found that the code for this key is 192, where the "Enter" key is 13 if that makes sense.

Here is the code I currently have & I don't understand why it isn't working:

  $(document).keypress(function(e) {
    if(e.which == 192) {
        //CODE I WANT TO EXECUTE GOES HERE
  }
})

Please help! I would use HTML but it is for a single .js file included on different pages around different sites. Also, I have read that there is code that only does this while in focus and I need it to work anywhere on the page.

27 is the code for the escape key. You can find the hex code for all the characters in this link ( http://asciitable.com/ ). Try this,

$(document).keyup(function(e) {
    if(e.which === 27 || e.keyCode === 27) {
        //CODE I WANT TO EXECUTE GOES HERE
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM