Responding to keyboard interactions (HTML)
Design and build apps that users can interact with through a hardware keyboard, the On-Screen Keyboard, or the touch keyboard.
Tip The info in this topic is specific to developing apps using JavaScript.
See Responding to keyboard interactions (XAML) for apps using C++, C#, or Visual Basic.
See Developing mouse controls (DirectX and C++) for apps using DirectX with C++.
Prerequisites: If you're new to developing apps using JavaScript, have a look through these topics to get familiar with the technologies discussed here.
Create your first Windows Store app using JavaScript
Roadmap for Windows Store apps using JavaScript
Learn about events with Quickstart: adding HTML controls and handling events
App features, start to finish:
Explore this functionality in more depth as part of our App features, start to finish series
User interaction, start to finish (HTML)
User interaction customization, start to finish (HTML)
User experience guidelines:
The platform control libraries (HTML and XAML) provide the full Windows user interaction experience, including standard interactions, animated physics effects, and visual feedback. If you don't need customized interaction support, use these built-in controls.
If the platform controls are not sufficient, these user interaction guidelines can help you provide a compelling and immersive interaction experience that is consistent across input modes. These guidelines are primarily focused on touch input, but they are still relevant for touchpad, mouse, keyboard, and stylus input.
- Guidelines for common user interactions
- Guidelines for optical zoom and resizing
- Guidelines for panning
- Guidelines for rotation
- Guidelines for Semantic Zoom
- Guidelines for visual feedback
Samples: See this functionality in action in our app samples.
User interaction customization, start to finish sample
Input: Device capabilities sample
Responding to the appearance of the on-screen keyboard sample
Overview
Keyboard input is an important part of an apps overall user interaction experience. The keyboard is indispensable to people with certain disabilities or users who just consider it a more efficient way to interact with an app. For example, users should be able to navigate your app by using Tab and arrow keys, activate UI elements by using Spacebar and Enter, and access commands by using keyboard shortcuts.
A well-designed keyboard UI is an important aspect of software accessibility. It enables users with vision impairments or who have certain motor disabilities to navigate an app and interact with its features. Such users might be unable to operate a mouse and instead rely on various assistive technologies such as keyboard enhancement tools, on-screen keyboards, screen enlargers, screen readers, and voice input utilities.
The most common type of keyboard is the external, hardware keyboard that is physically connected to a device. In addition to a hardware keyboard, Windows 8 provides two software keyboards:
The On-Screen Keyboard is a software keyboard you can use in Windows instead of the physical keyboard to type and enter data using touch, mouse, pen/stylus or other pointing device (a touch screen is not required). The On-Screen Keyboard is provided for systems that don't have a physical keyboard, or for users whose mobility impairments prevent them from using traditional physical input devices. The On-Screen Keyboard emulates most, if not all, the functionality of a hardware keyboard.
The touch keyboard is a visual, software keyboard used for text entry with touch input. The touch keyboard is not a replacement for the On-Screen Keyboard in Windows as it is used for text input only (it doesn't emulate the hardware keyboard) and appears only when a text field or other editable text control gets focus.
Note the On-Screen Keyboard has priority over the touch keyboard, which won't be shown if the On-Screen Keyboard is present.
Here are examples of the touch keyboard.
Windows - default layout:
Windows - thumb layout (might not be available in all languages):
Windows Phone - default layout:
Keyboard events
The following keyboard events can occur for both hardware and touch keyboards.
Event | Description |
---|---|
keydown | Occurs when any key is pressed. |
keyup | Occurs when any key is released. |
keypress | Occurs when an alphanumeric key is pressed. |
Keyboard events and focus
Controls in your UI generate keyboard events only when they have input focus. An individual control gains focus when the user clicks or taps directly on that control in the layout, or uses the Tab key to step into a tab sequence within the content area.
You can also call the focus method to force focus. This is necessary when you implement shortcut keys, because keyboard focus is not set by default when your UI loads. For more info, see the Shortcut keys example later in this topic.
For a control to receive input focus, it must be enabled and visible. This is the default state for most controls. When a control has input focus, it can raise and respond to keyboard input events as described later in this topic. You can also respond to a control that is receiving or losing focus by handling the focus, focusin, blur, and focusout events.
By default, the tab sequence of controls is the order in which they appear in the HTML. However, you can modify this order by using the tabIndex property. For more info, see Implementing keyboard accessibility (HTML).
Keyboard event handlers
We recommend that you add event handlers programmatically rather than declaratively in HTML (see Why you shouldn't set an event handler in markup).
There are three input events associated directly with keyboard interactions: keydown, keyup, and keypress.
Most event handlers take a single argument, an Event object that contains info about the event. Some of the most useful keyboard event properties include target, keyCode, and, if events are allowed to bubble, currentTarget.
Key
Typically, you listen to keyboard events to process a specific key value. To determine which key is pressed or released, check the keyCode value in the event data. keyCode returns a Key value. The Key enumeration includes all supported keys.
Keyboard shortcuts
In addition to implementing keyboard navigation and activation for your app, it is a good practice to implement shortcuts for your app's functionality. A shortcut is a keyboard combination (typically a letter key combined with a modifier key) that enhances productivity by providing an efficient way for the user to access app functionality.
An access key is a shortcut to a piece of UI in your app. Access keys consist of the Alt key and a letter key.
An accelerator key is a shortcut to an app command. Your app may or may not have UI that corresponds exactly to the command. Accelerator keys consist of the Ctrl and/or Shift keys and a letter key.
The x-ms-acceleratorKey attribute enables you to notify screen readers and other assistive technologies that an accelerator key exists. This attribute doesn't provide the accelerator key behavior. You must provide keyboard event handlers, such as keydown, keyup, and keypress, to process accelerator keys in your app.
Listening for and handling a keyboard event
Here, we show how to specify and define a handler for the keydown event.
Note These examples are taken from the Custom user interaction sample that supports the User interaction customization, start to finish (HTML) topic.
This event handler filters all keystrokes and processes only Left Arrow and Right Arrow keys.
// Key down handler.
// Take input from only the left and right arrow keys.
// Left: counter-clockwise rotation.
// Right: clockwise rotation.
this._element.addEventListener("keydown", function onKeyDownE(eventInfo) {
// Process keystroke only if color selected.
if (!that.selectedColor) {
return;
}
if (eventInfo.target === msGesture_ColorMixer.target) {
if (that._focus === false) {
return;
}
// Set increment or decrement value based on key pressed.
var increment;
if (eventInfo.keyCode === WinJS.Utilities.Key.leftArrow) {
increment = -1;
}
else if (eventInfo.keyCode === WinJS.Utilities.Key.rightArrow) {
increment = 1;
}
else return;
// Attach first contact and track input device type.
if (!that._pointerType) {
that._pointerType = "keyboard";
}
// Rotate the color mixer.
_Rotate(increment);
// Event tracking.
//document.getElementById("status").innerHTML += "keydown :: " + eventInfo.keyCode;
}
}, false);
Declare your shortcut keys in HTML markup by using the accesskey and x-ms-acceleratorkey attributes.
<div class="ColorSelector" id="colorSelector">
<!--
The aria-label attribute can be used when:
- the name of an element cannot be determined
programmatically from the content of the element.
- providing a visible label and/or tooltip is not
the desired user experience.
However, if the label text is visible on screen, you should
use aria-labelledby instead of aria-label.
-->
<div class="Color"
id="red"
aria-labelledby="redLabel redValue"
tabindex="0"
accesskey="R">
<span class="ColorLabel"
id="redLabel"
data-win-res="{textContent: 'colorpicker_red'}" />
<span class="ColorValue" id="redValue" />
</div>
<div class="Color"
id="green"
aria-labelledby="greenLabel greenValue"
tabindex="0"
accesskey="G">
<span class="ColorLabel"
id="greenLabel"
data-win-res="{textContent: 'colorpicker_green'}" />
<span class="ColorValue" id="greenValue" />
</div>
<div class="Color"
id="blue"
aria-labelledby="blueLabel blueValue"
tabindex="0"
accesskey="B">
<span class="ColorLabel"
id="blueLabel"
data-win-res="{textContent: 'colorpicker_blue'}" />
<span class="ColorValue" id="blueValue" />
</div>
<!--
Ctrl+S invokes the Save button and is exposed by a tooltip.
-->
<button
id="sendButton"
value="Send"
title="Send (Ctrl+S)"
x-ms-acceleratorkey="S">Send</button>
The framework supports keyboard functionality for setting focus or invoking elements, but you must implement keyboard event handlers, such as keydown, keyup, and keypress, to process accelerator keys in your app.
var sendButton = document.getElementById('sendButton');
sendButton.addEventListener('keyup', function(e) {
var itm = e.srcElement;
if (e.ctrlKey && e.keyCode === WinJS.Utilities.Key.s ) {
// Invoke send functionality.
}
});
Event modifiers
preventDefault cancels the default action of the event without stopping propogation through the Document Object Model (DOM). Use cancelable to check if the event is cancelable because calling preventDefault for a non-cancelable event has no effect.
stopPropagation cancels event propagation in the capturing or bubbling event phase. However, the event dispatches to all event listeners on the current target (regardless of capturing or bubbling) before the event flow stops. To completely prevent any remaining handlers from running, use the stopImmediatePropagation method instead.
The touch keyboard
Text input controls provide automatic support for the touch keyboard. When the user sets the input focus to a text control by using touch input, the touch keyboard appears automatically. When the input focus is not on a text control, the touch keyboard is hidden.
When the touch keyboard appears, it automatically repositions your UI to ensure that the focused element remains visible. This can cause other important areas of your UI to move off screen. However, you can disable the default behavior and make your own UI adjustments when the touch keyboard appears. For more info, see Responding to the appearance of the on-screen keyboard sample.
If you create a custom control that requires text input, but does not derive from a standard text input control, you can add touch keyboard support by implementing the correct UI Automation control patterns. For more info, see the Touch keyboard sample.
Key presses on the touch keyboard raise keydown and onkeyup events just like key presses on hardware keyboards. However, the touch keyboard will not raise input events for Ctrl+A, Ctrl+Z, Ctrl+X, Ctrl+C, and Ctrl+V, which are reserved for text manipulation in the input control.
User experience guidelines for supporting keyboard interactions
Here are some guidelines for supporting keyboard interactions.
General
Users should be able to accomplish all tasks supported by your app using only the hardware keyboard or the On-Screen Keyboard.Note The touch keyboard is used for text input only, not for app or system commands.
When your app starts, set initial keyboard focus on the element that users will intuitively (or most likely) interact with first. Typically, the most appropriate location is the main content view of the app so that a user can immediately scroll the content using the arrow keys. For more info on setting focus to specific controls, see focus.
Make sure the Tab and arrows keys move through content in a logical order.
Set the tabIndex attribute to a value that is greater than or equal to 0 for all interactive UI elements that are not in the tab order by default. Setting the tabIndex attribute is important because screen reader users navigate among interactive UI elements by using the Tab key.
Use the arrow keys as keyboard shortcuts for proper inner navigation among child elements of composite elements. If tree view nodes have separate child elements for handling expand–collapse and node activation, use the left and right arrow keys to provide keyboard expand–collapse functionality.
Ensure that each UI element that can be clicked can also be invoked with the keyboard.
Implement keyboard shortcuts for key app functionality. (A shortcut is a key combination that enhances productivity by providing an efficient way for the user to access app functionality.)
An access key is a shortcut to a UI element in your app. It consists of the Alt key and a letter key.
An accelerator key is a shortcut to an app command. Your app can have UI that corresponds exactly to the command. Accelerator keys consist of the Ctrl key and a letter key.
You must provide an easy way for users who rely on screen readers and other assistive technology to discover your app's shortcut keys. Declare your shortcut keys in your app's HTML markup by using the accessKey and -ms-AcceleratorKey attributes, and communicate shortcut keys by using tooltips, accessible names, accessible descriptions, or some other form of on-screen communication. Remember to document shortcut keys well in your app's help content.
For more guidance about implementing shortcut keys, see Shortcut keys in the Windows User Experience Guidelines.
Do not redefine the default keyboard shortcuts users expect from within every Windows Store app. See Keyboard shortcuts for a comprehensive list.
Hardware
Query the keyboard device capabilities (KeyboardCapabilities) to determine if a keyboard is attached and to identify what aspects of your app UI the keyboard hardware can access directly. For more info on querying device capabilities, see Quickstart: Identifying pointer devices.
Associate keyboard buttons with appropriate UI (back and forward buttons) in your app.
Visual feedback
- Use focus rectangles only with keyboard interactions. If the user initiates a touch interaction, make the keyboard UI gradually fade away. This keeps the UI clean and uncluttered.
- Don't display visual feedback if an element doesn't support interaction (such as static text).
- Display visual feedback concurrently for all elements that represent the same input target.
- Provide on-screen buttons (such as + and -) as hints for emulating touch-based manipulations such as panning, rotating, zooming, and so on.
For more general guidance on visual feedback, see Guidelines for visual feedback.
Related topics
Conceptual
Responding to user interaction
Implementing keyboard accessibility