views:

7113

answers:

5

How can I wire an event to fire if someone presses the letter 'g'?

(where is the character map for all the letters BTW?)

+7  A: 

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.

Here.

It's good to capture events from keyboard and you will find the character maps too. And good thing is ... it's jQuery.

Enjoy the demo and decide.

simplyharsh
+6  A: 
    <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

hunter
Use this! if (e.which == 103 || e.keyCode == 103 || window.event.keyCode == 103)
Trip
+20  A: 

What about js-hotkeys: The Javascript jQuery Hotkeys Plugin? (demo)

jQuery.Hotkeys plugin lets you easily add and remove handlers for keyboard events anywhere in your code supporting almost any key combination. It takes one line of code to bind/unbind a hot key combination.

Example: Binding 'Ctrl+c'

$(document).bind('keydown', 'ctrl+c', fn);
Ionut Staicu
Excellent plugin. The demo link doesn't work. Just go to http://code.google.com/p/js-hotkeys/ and download the zip file and run the demo from there. Thanks for the link.
Mario Awad
As another answer stated, at this time, jquery.hotkeys has been forked and the most up to date version is here: http://github.com/jeresig/jquery.hotkeys
David James
+4  A: 

You could also try the shortKeys jQuery plugin. Usage example:

$(document).shortkeys({
  'g': function () { alert('g'); }
});
Brant Bobby
+8  A: 

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

npad