Using keyboard shortcuts in Javascript

by Jean. 56 Comments -

If you want to enhance your web app, Javascript keyboards shortcuts is definitely something to consider. In this article, you’ll learn to use JS keyboard shortcuts, with and without the JQuery framework.

Keyboard shorcuts on the web, let’s talk about it

The most important thing to think about when implementing Javascript keyboard shortcuts on a web app is to avoid redefining shortcuts provided by the client’s browser. Imagine that you’re using a web app, you want to close the tab by pressing Cmd+W, and the web app trigger an action, just because the developer redefined a keyboard shortcut used by your browser…How annoying. This is why I recommend to avoid using the Ctrl (Windows) or Cmd (Mac) key for your web app shortcuts. You should definitely use another key as such as F1, for example.

As you may already know, Javascript have lots of useful event listeners. For keyboard shortcuts, we’ll use onkeyup,
which allow you to perform an action when a key is pressed. Then, we’ll just have to compare the returned value with the keyboard code associated with the key used by one of our custom defined keyboard shortcuts.

Keyboard codes are simple code consisting of 2 or 3 numbers. Each keyboard key have its own keyboard code. For exemple, the Ctrl key code is 17.

For a full reference of keyboard keys, scroll down to the end of this post.

Examples

In the following example, we’re simply going to verify the key pressed down by the user. If the key pressed are Ctrl+S, a function will be triggered.

First example, without JQuery:

var isCtrl = false;
document.onkeyup=function(e) {
    if(e.which == 17) isCtrl=false;
}document.onkeydown=function(e){
    if(e.which == 17) isCtrl=true;
    if(e.which == 83 && isCtrl == true) {
         alert('Keyboard shortcuts are cool!');
         return false;
    }
}

Example with the JQuery framework:

var isCtrl = false;$(document).keyup(function (e) {
if(e.which == 17) isCtrl=false;
}).keydown(function (e) {
    if(e.which == 17) isCtrl=true;
    if(e.which == 83 && isCtrl == true) {
        alert('Keyboard shortcuts + JQuery are even more cool!');
 	return false;
 }
});

In theses examples, we started by verifying that the Ctrl is pressed by the user. If yes, the initial value of the isCtrl variable is set to true. If the keys are released, isCtrl will be set to false again.

Once done, we have to verify that the second pressed key is S. As the shortcut consists of a keyboard combination, we also have to check that is isCtrl variable have true as a value.

If both the isCtrl variable ius set to true and the second pressed key is S, then we can trigger a Javascript alert to display a message. Of course, in a “real” web app, you’ll use a more useful function ;)

Keyboard codes reference

Key Keyboard code
Backspace 8
Tab 9
Enter 13
Shift 16
Ctrl 17
Alt 18
Pause 19
Capslock 20
Esc 27
Page up 33
Page down 34
End 35
Home 36
Left arrow 37
Up arrow 38
Right arrow 39
Down arrow 40
Insert 45
Delete 46
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
a 65
b 66
c 67
d 68
e 69
f 70
g 71
h 72
i 73
j 74
k 75
l 76
m 77
n 78
o 79
p 80
q 81
r 82
s 83
t 84
u 85
v 86
w 87
x 88
y 89
z 90
0 (numpad) 96
1 (numpad) 97
2 (numpad) 98
3 (numpad) 99
4 (numpad) 100
5 (numpad) 101
6 (numpad) 102
7 (numpad) 103
8 (numpad) 104
9 (numpad) 105
* 106
+ 107
- 109
. 110
/ 111
F1 112
F2 113
F3 114
F4 115
F5 116
F6 117
F7 118
F8 119
F9 120
F10 121
F11 122
F12 123
= 187
Coma 188
Slash / 191
Backslash \ 220
  • http://www.0window.com/blog/ Catrin W

    Implementing and using keyboard shortcuts can really enhance usability and accessibility of your site. But the question is do you have such a complex site and need for it.

  • http://www.howtogettallersecrets.com domjoel

    That’s pretty nifty. But wouldn’t it be a little bit hard at first for the users like me?

  • Pingback: ZioNews » Using keyboard shortcuts in Javascript

  • http://designawardsgallery.com/ Best CSS Gallery

    Thanks for the comprehensive list, I’ve been wondering are there any keyboard shortcuts for javascript. I’m not a very experienced user, but maybe they’ll appear to be useful

  • Pingback: How a Beginner Can Make Money Blogging | Internet Marketing

  • http://www.designstudio16.com saurabh shah

    wow ! this is really going to help to hide my code with ctrl+u … thnx for sharing … do u have something like to disable the viewsource file from Menu through script ?
    If so pls send me on my Email id.

    Thnks

  • http://contraculto.com contraculto

    @saurabh

    hide your code? that’s gonna be a tricky one. and why would you wan’t to do that, anyway?

  • Pingback: Using keyboard shortcuts in Javascript « Netcrema - creme de la social news via digg + delicious + stumpleupon + reddit

  • Pingback: The Technology Post for June 10th, 2009 - Jason N. Gaylord's Blog

  • http://nlsmith.com/ Nathan L Smith

    If you’re using Prototype.js, you might want to check out LivePipe UI’s HotKey class. It makes this stuff easy. http://livepipe.net/extra/hotkey

  • http://www.wprecipes.com Jean-Baptiste Jung

    @Nathan L Smith: Didn’t knew that class. Thanks for sharing!

  • http://www.quizzpot.com Hazel

    Thanks for providing the list and for the article. This will go to my favorite bookmarks :)

  • http://webhostingrating.com hello

    Hello there. Thank you for such an informative article. I am a Computer Engineering student. Now I have an edge to my classmates with this short cut keys. This will really help my in my course.

  • http://something4free.net/ Free Nintendo DSi

    Wha web apps would you consider when making a shortcut using javascript?

  • http://gunnerpress.com J Mehmett

    Thanks JBJ for sharing this. This is great contribution to the accessibility and simplicity of websites. I like it.

  • http://guitarherotips.co.cc Guitar Hero Tips

    thanks for this useful information but despite the many JavaScript libraries that are available today, I cannot find one that makes it easy to add keyboard shortcuts to your javascript app.

  • http://www.cherryessentials.co.uk James Montmorency Concentrate

    Superb tips all the shortcuts working fine, and to hide the view source which open by pressing ctrl+u
    is the classic one. These short cut keys definitely gonna cut short the task time. I’m gonna this blog bookmark..

  • http://www.easigo.co.uk Jenny Accident claim advice

    Thanks a lot for all the short cuts. They will definitely cut short my developing task and i will
    complete all tasks on time without delay..

  • http://www.gimmiethescoop.com/img/obamas-credit-card.png glensee919

    Thanks for this!

  • http://lap-topnotebooks.com/laptop-keyboard Laptop Keyboard

    This is a very useful and interesting you posted here. Thank you so much. I’ve learned a lot from it. Excellent posting. Good luck:-)

  • http://www.gnethosting.net Deniel | cheap web hosting

    Nice code sample and information. It is difficult to do it ourselves because there are thousand codes aailable but I always want to do it with my own hands(No malicious code threats).

  • Pingback: Using Keyboard Shortcuts in Javascript | Webmaster Sucks

  • http://www.rlhealthcareadvisors.com Healthcare Management

    Great help of code, always seeking for simple and soft code. it’s easy to implement for us again thx.

  • http://www.businessgas.com/ Business Gas

    Fantastic tips, I didnt even think about even trying this type of thing before I saw this

  • http://www.wheelchairguide.net Wheelchair Guide

    Interesting. Of course I always add keyboard shortcuts to my actual programs, but hadn’t really thought about doing it in a web app.

    Do you know how it affects performance?

  • Pingback: Alfredo Juarez » Blog Archive » Usando atajos de teclado en JavaScript

  • https://twitter.com/seo83 Seo83

    Really the tips that mentioned above are incredible. They will definitely decrease my task
    of code implementation..

  • http://pakidesigner.com tayyab

    very informative sharing.. thanks for the lovely post.

  • http://help.dottoro.com Edwin Cohen

    The which property is not supported by Internet Explorer.

  • http://www.totalactivemedia.nl Just a dude

    “The which property is not supported by Internet Explorer”

    Make sure u use “e.keyCode” insted of “wich” works for IE en FF

  • http://www.ianpatrickbuss.com/ Ian Patrick Buss

    I suggest a feature you implement onto your post… Alternating styled rows! it would help a lot!!!

  • http://blog.cherouvim.com/ cherouvim

    Why not use plain HTML and the accesskey attribute?

  • Pingback: 45 Fresh Useful JavaScript and jQuery Techniques and Tools « qeqnes | Designing. jQuery, Ajax, PHP, MySQL and Templates

  • Pingback: 45 Fresh Useful JavaScript and jQuery Techniques and Tools

  • Pingback: 45 Fresh Useful JavaScript and jQuery Techniques and Tools « Awesome Pixels

  • Pingback: Fresh Useful JavaScript and jQuery Techniques and Tools « Oviyas Blog

  • Pingback: 45 Fresh Useful JavaScript and jQuery Techniques and Tools | Awesome Pixels

  • Pingback: 45 Fresh Useful JavaScript and jQuery Techniques and Tools | thechatter.info

  • Pingback: 45 Fresh Useful JavaScript and jQuery Techniques and Tools | News, GTA, Sports, Business, Entertainment, World, Breaking - dasty.org

  • Pingback: uberVU - social comments

  • Pingback: 45 Fresh Useful JavaScript and jQuery Techniques and Tools « wwwba

  • Pingback: magichand Interaction -魔法交互 – 45 Fresh Useful JavaScript and jQuery Techniques and Tools

  • Pingback: Web Design Trends 2010 | i know idea

  • Pingback: The Current State of Web Design: Trends 2010 - Smashing Magazine

  • Pingback: 15 Stunning Tutorial Will Increase Your JavaScript Knowledge | [Re]Encoded.com

  • Pingback: The Current State of Web Design: Trends 2010 « Defonic International Solutions

  • Pingback: 45 Fresh Useful JavaScript and jQuery Techniques and Tools | Xiaoqi He ( Harry He ) – Official Blog – 贺孝琦官方博客

  • http://www.foxnews.com George M

    Yeah, I agree that implementing Javascript keyboard shortcuts on a web app is not easy, to say the least. However, the examples here really helped me, so thank you.

  • http://gemir.de GeMir

    Thanks for sharing! I changed your code a little bit (the original script doesn’t work in Chrome 15 and Firefox 8):

    isCtrl = false

    document.onkeydown = function(e) {
    if (e.keyCode == 17) {
    isCtrl = true
    }
    if (e.keyCode == 83 && isCtrl == true) {
    alert(‘Keyboard shortcuts are cool!’);
    isCtrl = false
    }
    }

  • Pauldb

    Thanks for the codes, but I wonder if there is anyway to use the “Play”, “Stop, “Next”… buttons of a keyboard, and if so, how ?

  • http://www.boatseatcushions.net/ Brant Jacinto

    I could save your beneficial report although composed

  • http://www.ystare.com/ Branden Clugston

    I just ought to say THANK YOU!!! i was battling to observed such a type information

  • http://burhanudin.web.id/ Muhamad Burhanudin

    Hello, i got problem about my code, i will use js hotkey to click submit form, but when i try this code doesn’t work correctly, can you help me?this is my code :

    shortcut.add(“Ctrl+B”,function() {
    document.getElementById(‘klik’).click();
    });

  • Benoist

    It’s awesome ! Do you know the keyboard code for the ² key ? I don’t find this information.

  • Daniel

    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.

  • http://www.dotnetmania.in Uthaiah Bollera

    Here is my sample piece of JavaScript code ::

    THIS SAMPLE CODE WORKS WITH “alt+” AND “cntrl+”

    document.onkeydown = function (e)
    {
    switch(e.altKey)
    {
    case true:
    console.log(“Alt key pressed”);
    switch(e.which)
    {
    case 65:
    alert(” alt + a is pressed”);
    break;
    case 66:
    alert(” alt + b is pressed”);
    break;
    case 67:
    alert(” alt + c is pressed”);
    break;
    case 68:
    alert(” alt + d is pressed”);
    break;
    case 69:
    alert(” alt + e is pressed”);
    break;
    case 70:
    alert(” alt + f is pressed”);
    break;
    case 71:
    alert(” alt + g is pressed”);
    break;
    case72:
    alert(” alt + h is pressed”);
    break;
    case 73:
    alert(” alt + i is pressed”);
    break;
    case 74:
    alert(” alt + j is pressed”);
    break;
    case 75:
    alert(” alt + k is pressed”);
    break;
    case 76:
    alert(” alt + l is pressed”);
    break;
    }
    }

    switch (e.ctrlKey) {
    case true:
    console.log(“Control key pressed”);
    switch (e.which) {
    case 65:
    alert(” cntrl + a is pressed”);
    break;
    case 66:
    alert(” cntrl + b is pressed”);
    break;
    case 67:
    alert(“cntrl + c is pressed”);
    break;
    case 68:
    alert(“cntrl + d is pressed”);
    break;
    case 69:
    alert(“cntrl + e is pressed”);
    break;
    case 70:
    alert(“cntrl + f is pressed”);
    break;
    case 71:
    alert(“cntrl + g is pressed”);
    break;
    case72:
    alert(“cntrl + h is pressed”);
    break;
    case 73:
    alert(“cntrl + i is pressed”);
    break;
    case 74:
    alert(“cntrl + j is pressed”);
    break;
    case 75:
    alert(“cntrl + k is pressed”);
    break;
    case 76:
    alert(“cntrl + l is pressed”);
    break;
    }
    }

    }