Keyboard shortcuts with jQuery

Keyboard shortcuts with jQuery

How can I wire an event to fire if someone presses the letter g?
(Where is the character map for all the letters BTW?)

Solutions/Answers:

Solution 1:

Since this question was originally asked, John Resig (the primary author of jQuery) has forked and improved the js-hotkeys project. His version is available at:

http://github.com/jeresig/jquery.hotkeys

Solution 2:

What about jQuery Hotkeys?

jQuery Hotkeys lets you watch for keyboard events anywhere in your code supporting almost any key combination.

To bind Ctrl+c to a function (f), for example:

$(document).bind('keydown', 'ctrl+c', f);

Solution 3:

I recently wrote a standalone library for this. It does not require jQuery, but you can use it with jQuery no problem. It’s called Mousetrap.

You can check it out at http://craig.is/killing/mice

Solution 4:

Well there are many ways. But I am guessing you are interested in an advanced
implementation. Few days back I was in same search, and I found one.

Related:  Google Chrome “Application Shortcut”: How to auto-load JavaScript?

Here.

It’s good for capturing events from keyboard and you will find the character maps too.
And good thing is … it’s jQuery. Check the demo on same page and decide.

An alternative library is here.

Solution 5:

    <script type="text/javascript">
        $(document).ready(function(){
            $("#test").keypress(function(e){
                if (e.which == 103) 
                {
                    alert('g'); 
                };
            });
        });
    </script>

    <input type="text" id="test" />

this site says 71 = g but the jQuery code above thought otherwise

Capital G = 71, lowercase is 103

Solution 6:

If you want just simple shortcuts (like 1 letter, for example just g) you could easily do it without a extra plugin:

$(document).keypress(function(e) {
  if(e.charCode == 103) {
    // Your Code
  }
});