Buttons with Keyboard Shortcut

Jake Howlett, 16 January 2001

Category: Forms; Keywords: button shortcut keyboard access key

If you buy in to the idea that, one day, all "work" will be carried out via the browser then you will probably want your applications to function as much like their non-browser equivalents as possible. This should, in turn, make them more user friendly.

One feature that is common to most native OS apps is the keybord shortcut. Consider the dialog box shown below:

Image

There are numerous ways of selecting either of the two buttons that I won't bother going in to. One way is to use the Alt+Y or Alt+N key combinations, denoted by the underlined letter on each button.

How could we do something like this in the browser. Using the <button> object, that's how. This was introduced in Internet Explorer 4 as a way to give more options to the developer when creating applications. Here is an example of how you can use it in a similar fashion to the dialog box above. Try clicking on it and then pressing Alt+X :



How do we do this. Simple. We use the "AccessKey" attribute of the button. The only thing to remember is not to use those letters reserved for the conventional browser menus (F, E, V, A, T, H & D). Here is the code behind the button:

<button onclick="alert('You have pressed the button');" accesskey="x" id="btnExample">E<u>x</u>ample</button>

The beauty of these button objects is that you can put almost anything in them. We can then use the <u> tag to underline the letter x and let the user know this is the shortcut key. Cool hey? You can even put images in them like this (I've played with the CSS too):



The code for this button is:

<button onclick="alert('You are currently at:\n' + window.location);" accesskey="w" id="btnWebAddress" style="border : 1px solid Gray; border-right: 2px solid Gray; border-bottom: 2px solid Gray; background-color : #F0F8FF;"><img src="/icons/vwicn070.gif"> <u>W</u>eb Address</button>