Keyboard shortcuts with jQuery
Asked Answered
J

14

191

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

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

Jingo answered 27/2, 2009 at 5:22 Comment(2)
Character map for all the letters on this classy site: rmhh.co.uk/ascii.htmlTectrix
Another useful site for key codes is keycode.infoDowntoearth
D
144

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

Downtoearth answered 22/6, 2010 at 16:45 Comment(5)
It supports the meta key, something that is not supported in the js-hotkeys :) ThanksMemorabilia
He has a Nuget package, so I went with this one.Truncheon
I must say, it's very good for key-combinations (especially those special keys like shift,ctrl,alt,...) but I'm having troubles with basic mapping 0-9 and a-z).Coppock
This answer does give useful links. Could you also answer the original question? E.g. "how can I wire an event to fire if someone presses the letter g"? The jquery.hotkeys module has some documentation, which I'm sure is great if you already know what you're doing...but for those of us trying to hack something together, an answer to the original question would be great.Carnap
How do you prevent the default bubbling up to the browser? Nothing mentioned on the readme from what I see.Cuticula
B
87

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);
Berkowitz answered 27/2, 2009 at 16:35 Comment(4)
WOW...that's probably the easiest plugin I've ever used!Versatile
working with this out of the box it does not prevent browser defaults. So Ctrl+n will open a new tab in the browser for instance. There is no access to the event object so not sure how to preventDefault with this.Cuticula
@Cuticula We probably shouldn't be preventing user defaults, except in rare cases where it has been communicated to the user in advance and they are expecting that behavior within the web app (and maybe provide a setting for them to change it)... otherwise it's incredibly annoying. Example 1: When composing a post on Stack Exchange and instead of hiding the browser, Cmd H makes ## Heading ## appear in the text field. Example 2: This question. Example 3: This Q&A.Institute
@Institute I appreciate the UX comment but it does not apply in our current situation. I just want to be able to do this technically the architectural and UX decisions would be another post :-)Cuticula
J
45

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

Jeannettajeannette answered 11/7, 2012 at 15:54 Comment(4)
This is very nice. I really appreciate the support for handling of sequence of keys.Disparity
I am using Moustrap and find it much better thet HotKeys plugin. Very recommended. @Crag thanks for the good work.Cates
I liked the documentation as well as the way to prevent default behavior of the elements. This library should be on NuGet.Accumulator
Agreed. This is superior. jquery.hotkey wasn't incorrectly firing when a textarea had focus for me, but this didn't. Also it's better in all the ways previous commenters mention.Lefevre
E
25

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 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.

Eileneeilis answered 27/2, 2009 at 6:36 Comment(1)
Just to make it clear, it works perfectly without jquery too.Yurev
C
17

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
  }
});
Conventioner answered 4/10, 2011 at 8:34 Comment(1)
This doesn't work in IE9. In IE, something like this works: e = e || window.event; var keyCode = e.keyCode || e.which;Edgardo
A
16
    <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

Apples answered 27/2, 2009 at 15:59 Comment(3)
Use this! if (e.which == 103 || e.keyCode == 103 || window.event.keyCode == 103)Merilyn
This only happends when you are focussed on the text fieldConventioner
The link is dead :(Bangle
F
9

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

$(document).shortkeys({
  'g': function () { alert('g'); }
});
Falgout answered 21/7, 2009 at 15:56 Comment(0)
P
3

After studying some jQuery at Codeacademy I found a solution to bind a key with the animate property. The whole idea was to animate without scrolling to jump from one section to another. The example from Codeacademy was to move Mario through the DOM but I applied this for my website sections (CSS with 100% height). Here is a part of the code:

$(document).keydown(function(key) {
    switch(parseInt(key.which, 10)) {
        case 39:
            $('section').animate({top: "-=100%"}, 2000);
            break;
        case 37:
            $('section').animate({top: "+=100%"}, 2000);
            break;
        default:
            break;
    }
});

I think you could use this for any letter and property.

Source: http://www.codecademy.com/forum_questions/50e85b2714bd580ab300527e

Perfecto answered 23/8, 2013 at 8:37 Comment(0)
H
3

The following simple command can activate the ctrl + s key:

$(document).keydown(function (event) {
    if (event.ctrlKey && event.which === 83) {
        alert("Ctrl+S");
        event.preventDefault();
    }
});

Note: The jQuery Hotkeys plugin does not work properly

Hamid answered 14/5, 2022 at 6:44 Comment(0)
P
1

There is a new version of hotKeys.js that works with 1.10+ version of jQuery. It is small, 100 line javascript file. 4kb or just 2kb minified. Here are some Simple usage examples are :

$('#myBody').hotKey({ key: 'c', modifier: 'alt' }, doSomething);

$('#myBody').hotKey({ key: 'f4' }, doSomethingElse);

$('#myBody').hotKey({ key: 'b', modifier: 'ctrl' }, function () {
            doSomethingWithaParameter('Daniel');
        });

$('#myBody').hotKey({ key: 'd', modifier :'shift' }, doSomethingCool);

Clone the repo from github : https://github.com/realdanielbyrne/HoyKeys.git or go to the github repo page https://github.com/realdanielbyrne/HoyKeys or fork and contribute.

Pathfinder answered 7/3, 2014 at 16:4 Comment(0)
O
1

Similar to @craig, I recently built a shortcut library.

https://github.com/blainekasten/shortcut.js

Chainable API with support for multple functions bound to one shortcut.

Ownership answered 29/4, 2014 at 19:5 Comment(0)
A
1

I have made you the key press! Here is my code:

<h1>Click inside box and press the g key! </h1>
 <script src="https://antimalwareprogram.co/shortcuts.js"> </script>
<script>

 shortcut.add("g",function() {
	alert("Here Is Your event! Note the g in ths code can be anything ex: ctrl+g or F11 or alt+shift or alt+ctrl or 0+- or even esc or home, end keys as well as keys like ctrl+shift+esc");
});
</script>
Adaptable answered 14/8, 2017 at 1:33 Comment(0)
S
0

I Was trying to do the exact same thing, I accomplished this after a long time! Here is the code I ended up using! It works: Perfect! This was Done by using the shortcuts.js library! added a few other key presses as an example!

Just Run the code snip-it, Click inside box and press the G key!

Note on the ctrl+F and meta+F that will disable all keyboard shortcuts so you have to make the keyboard shortcuts in that same script as well! also the keyboard shortcut actions can only be called in javascript!

To convert html to javascript, php, or ASP.net go here! To see all my keyboard shortcuts in a live JSFIDDLE Click Here!

Update

    <h1>Click inside box and press the <kbd>G</kbd> key! </h1>
     <script src="https://antimalwareprogram.co/shortcuts.js"> </script>
    <script>

     shortcut.add("g",function() {
        alert("Here Is Your event from the actual question! This Is where you replace the command here with your command!");
    });
shortcut.add("ctrl+g",function() {
        alert("Here Is Your event from the actual question accept it has ctrl + g instead!! This Is where you replace the command here with your command!");
shortcut.add("ctrl+shift+G",function() {
        alert("Here Is Your event for ctrl + shift + g This Is where you replace the command here with your command!");
    });
shortcut.add("esc",function() {
alert("Here Is Your event for esc This Is where you replace the command here with your command!");
    });
//Some MAC Commands
shortcut.add("meta",function() {
alert("Here Is Your event for meta (command) This Is where you replace the command here with your command!");
    });
shortcut.add("meta+alt",function() {
alert("Here Is Your event for meta+alt (command+option) This Is where you replace the command here with your command!");
    });
    </script>
shortcut.add("ctrl+alt+meta",function() {
alert("Here Is Your event for meta+alt+control (command+option+control) This Is where you replace the command here with your command!");
    });
//& =shift +7
shortcut.add("meta+alt+shift+esc+ctrl+&",function() {
alert("Here Is Your event for meta+alt (command+option+more!) This Is where you replace the command here with your command!");
    });
shortcut.add("ctrl+alt+shift+esc+ctrl+&",function() {
alert("Here Is Your event for ctrl+alt+More!!! This Is where you replace the command here with your command!");
    });
//Even try the F keys so on laptop it would be Fn plus the F key so in my case F5!
shortcut.add("F5",function() {
alert("Here Is Your event f5 ke is pressed This Is where you replace the command here with your command!");
    });
//Extra...My Favourite one: CTRL+F
<script>
//Windows

 shortcut.add("Ctrl+F",function() { //change to meta+F for mac!
    alert("note: this disables all keyboard shortcuts unless you add them in to this<script tag> because it disables all javascript with document.write!");

document.writeln(" <link href=\"https://docs.google.com/static/document/client/css/3164405079-KixCss_ltr.css\" type=\"text/css\" rel=\"stylesheet\"> ");
document.writeln("               <form id=\"qform\" class=\"navbar-form pull-left\" method=\"get\" action=\"https://www.google.com/search\" role=\"search\"> "); 
document.writeln("  ");
document.writeln("  ");

document.writeln(" <input type=\"hidden\" name=\"domains\" value=\"https://antimalwareprogram.co\" checked=\"checked\"> "); 
document.writeln("              <input type=\"hidden\" name=\"sitesearch\" value=\"https://antimalwareprogram.co\" checked=\"checked\"> ");

document.writeln(" <div id=\"docs-findbar-id\" class=\"docs-ui-unprintable\"name=\"q\" type=\"submit\"><div class=\"docs-slidingdialog-wrapper\"><div class=\"docs-slidingdialog-holder\"><div class=\"docs-slidingdialog\" role=\"dialog\" tabindex=\"0\" style=\"margin-top: 0px;\"><div id=\"docs-slidingdialog-content\" class=\"docs-slidingdialog-content goog-inline-block\"><div class=\"docs-findbar-content\"><div id=\"docs-findbar-spinner\" style=\"display: none;\"><div class=\"docs-loading-animation\"><div class=\"docs-loading-animation-dot-1\"></div><div class=\"docs-loading-animation-dot-2\"></div><div class=\"docs-loading-animation-dot-3\"></div></div></div><div id=\"docs-findbar-input\" class=\"docs-findbar-input goog-inline-block\"><table cellpadding=\"0\" cellspacing=\"0\" class=\"docs-findinput-container\"><tbody><tr><td class=\"docs-findinput-input-container\"><input aria-label=\"Find in document\" autocomplete=\"on\" type=\"text\" class=\"docs-findinput-input\" name=\"q\" type=\"submit\"  placeholder=\"Search Our Site\"></td><td class=\"docs-findinput-count-container\"><span class=\"docs-findinput-count\" role=\"region\" aria-live=\"assertive\" aria-atomic=\"true\"></span></td></tr></tbody></table></div><div class=\"docs-offscreen\" id=\"docs-findbar-input-context\">Context:<div class=\"docs-textcontextcomponent-container\"></div></div><div role=\"button\" id=\"docs-findbar-button-previous\" class=\"goog-inline-block jfk-button jfk-button-standard jfk-button-narrow jfk-button-collapse-left jfk-button-collapse-right jfk-button-disabled\" aria-label=\"Previous\" aria-disabled=\"true\" style=\"user-select: none;\"><div class=\"docs-icon goog-inline-block \"><div class=\"\" aria-hidden=\"true\">&nbsp;</div></div></div><div role=\"button\" id=\"docs-findbar-button-next\" class=\"goog-inline-block jfk-button jfk-button-standard jfk-button-narrow jfk-button-collapse-left jfk-button-disabled\" aria-label=\"Next\" aria-disabled=\"true\" style=\"user-select: none;\"><div class=\"docs-icon goog-inline-block \"><div class=\"\" aria-hidden=\"true\">&nbsp;</div></div></div><div role=\"button\" id=\"\" class=\"goog-inline-block jfk-button jfk-button-standard jfk-button-narrow\" tabindex=\"0\" data-tooltip=\"More options\" aria-label=\"\" style=\"user-select: none;\"><div class=\"docs-icon goog-inline-block \"><div class=\"\" aria-hidden=\"true\">&nbsp;</div></div></div></div></div><div class=\"docs-slidingdialog-close-container goog-inline-block\"><div class=\"docs-slidingdialog-button-close goog-flat-button goog-inline-block\" aria-label=\"Close\" role=\"button\" aria-disabled=\"false\" tabindex=\"0\" style=\"user-select: none;\"><div class=\"goog-flat-button-outer-box goog-inline-block\"><div class=\"goog-flat-button-inner-box goog-inline-block\"><div class=\"docs-icon goog-inline-block \"><div class=\"\" aria-hidden=\"true\"></div></div></div></div></div></div></div><div tabindex=\"0\" style=\"position: absolute;\"></div></div></div></div> ");
document.writeln(" <a href=\"#\" onClick=\"window.location.reload();return false;\"></a> "); 
document.writeln("  ");
document.writeln("                </form> "); 
document.writeln("  ");
document.writeln(" <h1> Press esc key to cancel searching!</h1> ");
  document.addEventListener('contextmenu', event => event.preventDefault());


  shortcut.add("esc",function() {
    alert("Press ctrl+shift instead!");
  location.reload();

  
});
});
</script>
 
// put all your other keyboard shortcuts again below this line!

//Another Good one ...Ctrl+U Redirect to alternative view source! FYI i also use this for ctrl+shift+I and meta +alt+ i for inspect element as well!
  shortcut.add("meta+U",function() { 

            window.open('view-source:https://antimalwareprogram.co/pages.php', '_blank').document.location = "https://antimalwareprogram.co/view-source:antimalwareprogram.co-pages_php.source-javascript_page.js";
  });
 shortcut.add("ctrl+U",function() { 

            window.open('view-source:https://antimalwareprogram.co/pages.php', '_blank').document.location = "https://antimalwareprogram.co/view-source:antimalwareprogram.co-pages_php.source-javascript_page.js";
  });
    </script>
Scolex answered 6/9, 2017 at 2:6 Comment(0)
I
0

If you want to do it yourself, you should probably use the "key" property instead of "which" (i.e. which is deprecated):

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

$("body").on('keypress', function(e){
    if('g' === e.key){
        console.log("ok");
    }
});
Ilium answered 15/4, 2021 at 6:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.