Open Source Software Technical Articles

Want the Best of the Wazi Blogs Delivered Directly to your Inbox?

Subscribe to Wazi by Email

Your email:

Connect with Us!

Current Articles | RSS Feed RSS Feed

Easy Keyboard Shortcuts for Web Pages

  
  
  

Web application developers should strive to provide as good an interface for their web apps as other programmers do with desktop programs. One simple enhancement is to provide keyboard shortcuts to main functions, as sites such as Gmail, Google Docs, and Twitter do. Experienced users welcome keyboard shortcuts because they offer the ability to work faster, letting users perform operations without having to remove their hands from the keyboard.



Since the Web's early days, HTML has offered access keys, which let you quickly navigate to a specific field by means of an ALT+key combo. More recently, and more sophisticated, are hot keys, which are specific to a single application and let users invoke any function or perform any given procedure. You'll probably want to use both types of shortcuts in your web pages, so let's quickly look at access keys, then move on to implementing hot keys, first by hand, then in a much easier way by using the Keyboard Shortcuts JavaScript library, either directly or through jQuery.



Access Keys



Access keys provide quick shortcuts to navigate to a given web form field. If you set the accesskey attribute of a form field to, say, "A," users can quickly go to the corresponding field by pressing a key combination. The exact combination depends on the browser: CTRL+A or CTRL+OPT+A on a Mac, or ALT+A on Windows or Linux, except on Firefox, which requires ALT+SHIFT+letter in order to reserve ALT+letter combinations for its own usage, and Opera, which expects SHIFT+ESC in order to list the set of available access keys. Standards, anybody? The code below defines a simple web form with three fields, each with an access key.




<html>
<head>
    <title>Keyboard Access Keys Demo</title>
</head>
<body>
    <h1>Keyboard Access Keys Demo</h1>
    <label for="nameField"><u>N</u>ame:</label>
    <input id="nameField" type="text" accesskey="n" title="Press access key N to enter the user's name"/>
    <br>
    <label for="addressField"><u>A</u>ddress:</label>
    <input id="addressField" type="text" accesskey="A" title="Press access key A to enter the user's address"/>
    <br>
    <label for="phoneField">P<h></u>one:</label>
    <input id="phoneField" type="text" accesskey="H" title="Press access key H to enter the user's phone number"/>
    <br>
</body>
</html>


Browsers do not provide any visual feedback as to available access keys, so it's up to you as the form designer to provide some cues to users. I opted for the common solution of underlining a letter in the label, because that convention is often used on desktop programs. You could use the title attribute, but a user would have to use the mouse and hover over the field in order to learn about the shortcut.



[caption id="attachment_178275" align="alignnone" width="300" caption="Opera requires pressing SHIFT+ESC to provide a menu of available access keys"][/caption]

Despite access keys being a standard, you can still face problems with specific browsers that reserve certain key combinations for their own usage. For example, in Firefox, you cannot use P or S as access keys (because ALT+SHIFT+P and ALT+SHIFT+S are reserved by Mozilla, in addition to ALT+letter combos) unless you are willing to change the browser's configuration by navigating to about:config and setting ui.key.contentAccess to 4 and ui.key.chromeAccess to 5. No web developers should expect their application to depend on users making this sort of change. You might consider browser detection in order to use alternative combinations, but this approach still requires some experimentation in order to verify that everything works as planned. So, generally speaking, you have to do extensive testing to ensure that your access keys actually work as planned.

19a98812-f823-48dc-841e-bf029c63c6d7


Hot Keys



Now that we have dealt with access keys and HTML, let's move on to some programming, as hot keys do require some JavaScript work and are a tad trickier to get right. If you want to define your own hotkeys, the standard solution would have you define a document.onkeydown function (or document.onkeypress, but be aware that there are slight differences in the actual keycodes returned by each), detect what key and which modifier keys (Shift, Alt, Control, etc.) were pressed, and, depending on all that, take an appropriate course of action. For example:




<html>
<head>
    <title>Keyboard Hot Keys Demo #1</title>
    <script type="text/javascript">
        document.onkeydown = function(e) {
            e = e || window.event; // because of Internet Explorer quirks...
            k = e.which || e.charCode || e.keyCode; // because of browser differences...

            if (k == 49 && !e.altKey && !e.ctrlKey && !e.shiftKey) {
                document.getElementById("check1").checked = true;
            } else if (k == 65 && e.altKey && !e.ctrlKey && !e.shiftKey) {
                document.getElementById("check2").checked = true;
            } else if (k == 66 && e.altKey && e.ctrlKey && !e.shiftKey) {
                document.getElementById("check3").checked = true;
            } else if (k == 90 && e.altKey && e.ctrlKey && e.shiftKey) {
                document.getElementById("check4").checked = true;
            } else {
                return true; // it's not a key we recognize, move on...
            }
            return false; // we processed the event, stop now.
        }
    </script>
</head>
<body>
    <h1>Keyboard Hot Keys Demo #1, with pure JavaScript</h1>
    <input type="checkbox" id="check1">Key "1" was pressed<br>
    <input type="checkbox" id="check2">Key combo "ALT+A" was pressed<br>
    <input type="checkbox" id="check3">Key combo "ALT+CTRL+B" was pressed<br>
    <input type="checkbox" id="check4">Key combo "ALT+CTRL+SHIFT+Z" was pressed<br>
    <br>
    A nice box to type in: <input type="text">
</body>
</html>


The screen defined by the code above, when loaded, looks like this:





You can type in the text box, or use any of several keys that tick designated checkboxes. Of course, you have to consider some browser quirks in order to determine the keycode that corresponds to whatever the user pressed. Also, you'll have to remember the codes for all keys, particularly in the case of special and function keys. Don't forget to cancel the keyboard event if you recognized the key combo, or else the hot key will "bubble up" and also be interpreted by the browser, which you don't want to happen!



Note the first couple of lines in the onkeydown function, which take into account browser quirks and differences, and the return lines that allow or block the default key processing. While this sort of coding works, it's not very clear, and cannot easily conditionally enable or disable specific actions; for example, a "Save" function shouldn't be enabled unless something has been entered, and valid keypresses (such as "1" in the example) shouldn't be processed while entering text. Also, being able to dynamically add or remove shortcuts would be a plus.



While you could enhance the code to allow for these requirements, you can do better by using the Keyboard Shortcuts function, as we shall see.



Hot Keys: An Easier Way



For a better way to work with hotkeys, we need simple methods to add and remove function processing code. Specifically for single-key hotkeys, we must be able to enable and disable hotkey recognition and processing in input and textarea fields, so users can type normally. We also want to be able to tie events to specific fields, instead of associating them with the complete document.



The Keyboard Shortcuts JavaScript library provides all these features. Download it and let's rework our example to use it:




<html>
<head>
    <title>Keyboard Hot Keys Demo #2</title>
    <script src="shortcut.js" type="text/javascript"></script>
    <script type="text/javascript">
        function initKeys() {
            shortcut.add("1", function() {
                document.getElementById("check1").checked = true;
            },
            {"disable_in_input":true}
            );

            shortcut.add("Alt+A", function() {
                document.getElementById("check2").checked = true;
            },
            {"target":document.getElementById("myText")}
            );

            shortcut.add("Alt+Ctrl+B", function() {
                document.getElementById("check3").checked = true;
            });

            shortcut.add("Alt+Ctrl+Shift+Z", function() {
                document.getElementById("check4").checked = true;
            });
        }

        window.onload = initKeys;
    </script>
</head>
<body>
    <h1>Keyboard Hot Keys Demo #2, with "Keyboard Shortcuts" library</h1>
    <input type="checkbox" id="check1">Key "1" was pressed<br>
    <input type="checkbox" id="check2">Key combo "ALT+A" was pressed<br>
    <input type="checkbox" id="check3">Key combo "ALT+CTRL+B" was pressed<br>
    <input type="checkbox" id="check4">Key combo "ALT+CTRL+SHIFT+Z" was pressed<br>
    <br>
    A nice box to type in: <input type="text" id="myText"><br>
    Another nice box to type in: <input type="text" id="myText2"><br>
    <button type="button" onclick="shortcut.remove('ALT+A');">Disable the ALT+A hotkey</button>
</body>
</html>


And here's a screenshot showing that some hotkeys were pressed:



[caption id="attachment_178277" align="alignnone" width="300" caption="The Keyboard Shortcuts library makes defining hot keys much easier"][/caption]

To add a hotkey, we call the shortcut.add() function. (shortcut is a JavaScript variable created by the shortcut.js script.) This function has three parameters:




    • What key to recognize, such as "1" or "ALT+A." You can specify the ALT, CTRL (or CONTROL), META, and SHIFT modifiers in any order. The actual key can be in upper or lower case. In addition to alphanumeric and other character keys, you can also include special keys such as Backspace, cursor keys (Down, Left, Right, Up), Delete, Home and End, Insert, Pause, Page_Up and Page_Down, Return (or Enter), Space, Tab, and function keys F1 to F12.

    • The callback function to call; this function takes no parameters.

    • An (optional) associative array with specific options.



By using the third parameter, you can refine how and when hotkeys are recognized:




    • type lets you process keydown (default), keyup>, or keypress events.

    • disable_in_input is a boolean value (default: false) that enables and disables the hotkey process when the user is in an input text area. In the example, I used this option for the "1" hotkey.

    • target is a DOM element (default: document) to which the hotkey should be attached. In the example, I attached the ALT+A event only to the first textbox, so it won't work in the second.

    • propagate is a boolean value (default: false) that specifies whether the key event processing should stop, or if it should propagate to other possible handlers.



You can also remove a hotkey shortcut with a statement like shortcut.remove("ALT+A");, but be careful; there is a bug in the current version of the library, and if you assigned several methods to the same hotkey with different target values, only the latest shortcut will be removed, and the rest will still be active. If you load the page above and click on the button at the bottom, the ALT+A function will be disabled.



The jQuery Way



If you use jQuery for web development, of course you could still use the Keyboard Shortcuts library, and work with $(...) instead of document.getElementById(...), but you can go one better by using the Hotkeys plugin. This plugin is based upon (but independent from) the Keyboard Shortcuts library, and works in a jQuery-ish way by using bind and unbind methods to set and reset hot keys. Download the plugin and you'll be able to write hotkey processing code as below.




<html>
<head>
    <title>Keyboard Hot Keys Demo #3</title>
    <script src="jquery.min.js" type="text/javascript"></script>
    <script src="jquery.hotkeys.js" type="text/javascript"></script>
    <script type="text/javascript">

        function onAltA() {
            document.getElementById("check2").checked = true;
        }

        function initKeys() {
            $(document).bind("keydown", "1", function() {
                document.getElementById("check1").checked = true;
            });

            $("#myText").bind("keydown", "Alt+A", onAltA);

            $(document).bind("keydown", "Alt+Ctrl+B", function() {
                document.getElementById("check3").checked = true;
            });

            $(document).bind("keydown", "Alt+Ctrl+Shift+Z", function() {
                document.getElementById("check4").checked = true;
            });
        }

        window.onload = initKeys;
    </script>
</head>
<body>
    <h1>Keyboard Hot Keys Demo #3, with jQuery plugin</h1>
    <input type="checkbox" id="check1">Key "1" was pressed<br>
    <input type="checkbox" id="check2">Key combo "ALT+A" was pressed<br>
    <input type="checkbox" id="check3">Key combo "ALT+CTRL+B" was pressed<br>
    <input type="checkbox" id="check4">Key combo "ALT+CTRL+SHIFT+Z" was pressed<br>
    <br>
    A nice box to type in: <input type="text" id="myText"><br>
    Another nice box to type in: <input type="text" id="myText2"><br>
    <button type="button" onclick="$('#myText').unbind('keydown', onAltA);">Disable the ALT+A hotkey</button>
</body>
</html>


The web page that this code creates looks exactly like the example with the Keyboard Shortcuts library, so we'll skip a screenshot.



The bind() method here associates a function with a keyboard event. By default, events are not recognized in text areas; in order to get ALT+A to work in the first text box, you must bind it specifically. If you don't wish to propagate an event, use the preventBubble parameter in the jQuery bind call. There's an error in the documentation about how to unbind an event; the correct way is $().unbind(theKeyCombination, theFunction) as shown in the web page above. (Also note that we had to use a named function, instead of an anonymous one, in order to be able to unbind the event code.)



In Conclusion



Despite browser differences and restrictions, the use of access keys and hot keys enhances the usability of your web applications, and makes advanced users happier without bothering common users. Use them widely in your own code; it isn't that hard with the Keyboard Shortcuts library and code like we've seen here.




This work is licensed under a Creative Commons Attribution 3.0 Unported License
Creative Commons License.


This work is licensed under a Creative Commons Attribution 3.0 Unported License
Creative Commons License.

Comments

nice javascript used for the key board shortcuts. its very easy to use it in wordpress.. 
 
Thanks for the post !
Posted @ Sunday, September 16, 2012 2:15 AM by mailfeed
very helpful and easy!!! 
thanks
Posted @ Tuesday, March 19, 2013 2:43 AM by anki
 
It is necessary to take a pleasure junketing to relax our body and mood, here suggest you different places to travel. Take Junketing Travel guides,Travel advice,tips and destination information to inspire you from Lonely Planet. Get travels Let's help you find the best way to enjoy all the wonder,and excitement getstravel.com has to offer. Get travel
Posted @ Friday, May 03, 2013 1:23 AM by April
 
Tourism guide to help you plan where to go, when to visit, and what to do. Choose from the best vacation destinations in the world. Let tourism Read travelalones's reviews to find the best travel destinations, hotels and restaurants. Plan your trip online with. Travel alone The latest travel information, deals, guides and reviews from get Get journey
Posted @ Friday, May 03, 2013 1:24 AM by Bntonia
Taste good wine,know more wine knowledge,and enjoy the feeling of bouquet lingering on the tip of the nose. For a journey Guide to grape wine and liquor,including famous grape wine,new products and trends, Drink Good Wine offers a range of wines from around the world Smell Liquor
Posted @ Friday, May 03, 2013 1:25 AM by Alexia
 
Buy Age of Wushu Taels, The prices are worth spending, deliveries are usually completed within a few minutes. 
Age of Wushu Taels If you are not 100% satisfied with our service, you may request a refund at any time before delivery.Age of Wushu GoldAge of Wushu Taels,buy Age of Wushu Taels,cheap Age of Wushu Taels,Age of Wushu Gold,Age of Wushu Money,Age of Wushu currency Age of Wushu currency
Posted @ Friday, May 03, 2013 1:25 AM by Blthea
Retain these kinds of giving thoughts later on as well. Really It was What My partner and i was looking for, as well as I will be happy to be able to cam below! Thanks intended for giving the knowledge around these kinds of.cool camping gear 
Posted @ Tuesday, June 04, 2013 11:03 AM by cool camping gear
I’m bookmarking the particular site as well as would likely post this to be able to my personal man friends who would want to consider this.van insurance online quote 
Posted @ Tuesday, June 04, 2013 11:04 AM by June 04,
women's designer shoes 
Thanks a good deal as well as preserve giving the knowledge. Retain upgrading the knowledge for everyone. Thanks.
Posted @ Tuesday, June 04, 2013 11:05 AM by women's designer shoes
if you assigned several methods to the same hotkey with different target values, only the latest shortcut will be removed, and the rest will still be active.
Posted @ Friday, June 07, 2013 9:07 AM by Selling Structured Settlement
Superb site as well as I desired to publish a note to be able to tell you, ""Good job""! I’m pleased I discovered this blog. Amazing as well as superb work! Your website site possesses introduced myself a lot of the methods i always like. Appreciate it pertaining to sharing this specific.For more inf Click on Hyundai Tampa
Posted @ Sunday, September 01, 2013 8:56 AM by Hyundai Tampa
I really realize for your brilliant Efforts on spending time to post this information in a simple and regular manner, so That viewer and readers can easily understand the concept. I Efforts must appreciate you posting these on information. 
Posted @ Friday, October 04, 2013 8:04 AM by History of the loan sharks
This is a really cool blog. I am a frequent visitor of this site. Read the news on the earthquake. It was really sad news. Keep posting more such information’s. All the very best to you and your team. Good llegalseal
Posted @ Wednesday, October 30, 2013 9:40 PM by legalseal
Its amazing to see someone put so much passion into a subject. I’m glad I came across this. I’m glad I took the time to read on past the first paragraph. You’ve got so much to say, so much to offer. I hope people realize this and look into your page.
Posted @ Thursday, October 31, 2013 9:27 PM by zanzibar hotels
Superb website also as I desired to publish a note to be ready to tell you, "Good job"! I’m happy I discovered this web log. wonderful also as excellent work! Your {website|web website} site possesses introduced myself lots of the ways i continuously like. Appreciate it concerning sharing this specific. http://www.nectarclaims.co.uk
Posted @ Thursday, November 14, 2013 2:18 AM by Nadeem Hoban
But this approach still requires some experimentation in order to verify that everything works as planned. So, generally speaking, you have to do extensive testing to ensure that your access keys actually work as planned.
Posted @ Saturday, December 14, 2013 3:36 AM by dell laptops black friday 2013
Really It was What My partner and i was looking for, as well as I will be happy to be able to cam below! Thanks intended for giving the knowledge around
Posted @ Monday, December 23, 2013 1:21 AM by NYC child support
You could use the title attribute, but a user would have to use the mouse and hover over the field in order to learn about the shortcut.
Posted @ Tuesday, December 24, 2013 12:05 AM by symptoms of alcohol abuse
I Efforts must appreciate you posting these on information.
Posted @ Monday, January 13, 2014 1:27 AM by http://www.chicagopartylimousine.com/
The code below defines a simple web form with three fields, each with an access key.
Posted @ Monday, January 13, 2014 2:14 AM by http://www.ffxivwiki.eorzeaendgame.com
Browsers do not provide any visual feedback as to available access keys, so it's up to you as the form designer to provide some cues to users.
Posted @ Saturday, January 18, 2014 4:52 AM by New Bruno Mars Songs
Experienced users welcome keyboard shortcuts because they offer the ability to work faster
Posted @ Saturday, January 18, 2014 6:44 AM by Rihanna
Wholesale Cheap Sexy Lingerie, Halloween Costumes, Clubwear And Corsets Manufacturers From China Suppliers. 
Overbust Corset 
Flapper Costumes 
Wholesale Sexy Clubwear
Posted @ Monday, January 20, 2014 8:09 PM by Wholesale Sexy Clubwear
letting users perform operations without having to remove their hands from the keyboard.
Posted @ Wednesday, January 22, 2014 6:13 AM by 2014 MLM Opportunity
Fantastic! Thank you very much for sharing this fantastic post. I really like this site as well.
Posted @ Thursday, January 23, 2014 3:43 AM by Natural nutrition supplements
The code below defines a simple web form with three fields, each with an access key.
Posted @ Tuesday, January 28, 2014 6:32 AM by iifym guide
Specific to a single application and let users invoke any function or perform any given procedure.
Posted @ Wednesday, January 29, 2014 12:59 AM by infusionsoft reviews 2014
Very nice post! I just recently started reading your article, but I look forward to learning more from you in the future.
Posted @ Friday, January 31, 2014 1:13 AM by yamaha portable generator reviews
You'll probably want to use both types of shortcuts in your web pages
Posted @ Friday, January 31, 2014 3:07 AM by http://www.youtube.com/watch?v=ptpnJY1Kaks
I Efforts must appreciate you posting these on information.
Posted @ Tuesday, March 11, 2014 8:27 AM by Gifts to Ukraine
Excellent post. It makes me realize the energy of words. I learn a lot, thank you! Wish you make a further progress in the future.
Posted @ Friday, March 28, 2014 2:03 AM by is bubblegum casting legitimate
Great blog. All posts have something to learn. Your work is very good and i appreciate you and hopping for some more informative posts. william gomes 
Posted @ Tuesday, April 29, 2014 6:30 AM by lewissmith
Really great post, Thank you for sharing This knowledge.Excellently written article, if only all bloggers offered the same level of content as you, the internet would be a much better place. Please keep it up! child molester registry 
Posted @ Monday, May 05, 2014 6:59 AM by frankgary
I am glad it was an enjoyable experience for you. I think that you should definitely do it again sometime and hopefully I will be able to make it to that one..
Posted @ Friday, June 06, 2014 3:25 PM by Pressrelease - Press Release Singapore
Excellent stuff from you, man. I’ve read your things before and you are just too awesome. I adore what you have got right here. You make it entertaining and you still manage to keep it smart.This is truly a great blog thanks for sharing learn java
Posted @ Friday, June 20, 2014 1:57 AM by karenchun
Thank you for sharing this article. I like it. Keep on writing this type of great stuff. 
Posted @ Monday, July 14, 2014 3:53 AM by medicine ball cleans weight
Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work. https://www.google.com/+MotorsCoThai
Posted @ Wednesday, July 16, 2014 3:41 AM by kevinmary
I just found this, really good. I'm glad to be here. Here nyomtató patron you can find some interesting things to turn the printer.
Posted @ Tuesday, July 29, 2014 1:41 PM by John
Post Comment
Name
 *
Email
 *
Website (optional)
Comment
 *

Allowed tags: <a> link, <b> bold, <i> italics