Scripts are keyboard accessible. If the content affected by scripting is not accessible, an alternative is provided.


Rationale

Scripting, including JavaScript® and the standard version ECMAScript, enables Web developers to enhance sites with dynamic content, visual effects, user interaction, and client-side processing. Scripts can update HTML content and perform visual enhancements to a Web site. They can respond to many types of manual and automatic events, including the loading of a Web page, the selection of an item in a menu, and the submission of a form. Due to the virtually limitless ability of scripts to affect most any content, discussing the techniques for making the use of JavaScript accessible is complex and sometimes challenging.

The general approach to making scripting accessible is to ensure that the functionality of the scripts can be accessed from a keyboard and that the information (content) is available to assistive technologies.

Scripts that provide both of these features are considered directly accessible. If one or both of the above cannot be achieved, then additional techniques are used to reduce the need for scripting or to provide equivalent content that does not rely on script functionality. This checkpoint provides recommendations and techniques for accessible scripting.

Required development and unit test techniques


To comply with this checkpoint, you must meet all of the following techniques. These techniques are defined in WCAG 2.0 Level A Success Criterion 2.1.1 (link resides outside of ibm.com).

  1. Functions: Use both keyboard and other device-specific functions.
  2. JavaScript actions: Make JavaScript actions keyboard accessible.
  3. Information available: Ensure that information exposed or changed via scripting is available to assistive technologies.

Note: The examples presented in the techniques are not exhaustive. They are meant to illustrate the spirit of this checkpoint.

At this time WAI-ARIA examples are only fully supported in Firefox version 3.6 or later and version JAWS 12 or later. If your product needs to be accessible in Internet Explorer and mobile Safari/VoiceOver, one or more of the required HTML/CSS specific techniques must be implemented, as well as a WAI-ARIA technique. When WAI-ARIA becomes an approved W3C recommendation and Internet Explorer and mobile Safari/VoiceOver fully support it, then WAI-ARIA techniques alone will be sufficient to comply with this checkpoint.

Applications that provide WAI-ARIA must add the following statement to the checkpoint comments column of the Web Accessibility Checklist:

Note: This product uses WAI-ARIA to comply with this checkpoint. WAI-ARIA is supported on Windows using Firefox version 3.6 or later and JAWS version 12 or later, and supported on iOS v5.0 and later using Safari and VoiceOver.

Script examples

  1. Functions: Use both keyboard and other device-specific functions.

    To comply with this technique, you must implement all of the following examples.

    Script example 1

    In the following example, the developer wants additional text to be displayed when a user with a mouse puts the cursor over the image (onMouseOver). To make this type of functionality accessible, onFocus and onBlur must also be used. In addition, because this is essentially an "image-swap", alt text must be added to the image, so that visually impaired users have access to the content as well. The image-swap below can be executed with a mouse or with a keyboard.

    Accessibility - The quality of being accessible, or of admitting approach; receptibility.

    The code for the above example is as follows:

    <a href="webscripts_eventhandlers.html#imageswap" onmouseover="document.images['ex1pic2'].src = ex1on.gif';"
    onfocus="document.images['ex1pic2'].src = 'ex1on.gif';"
    onmouseout="document.images['ex1pic2'].src = 'ex1off.gif';"
    onblur="document.images['ex1pic2'].src = 'ex1off.gif';"><img src="ex1off.gif" width="289" height="79" id="ex1pic2"
    alt="Accessibility - The quality of being accessible, or of admitting approach; receptibility." /></a>

    The following table suggests keyboard event handlers to pair with mouse event handlers.


    Mapping of event handlers for the mouse to the keyboard
    Use... ...with

    mousedown

    Keydown

    mouseup

    Keyup

    Click [1]

    keypress [2]

    mouseover

    focus

    mouseout

    blur

    Script example 2

    Rich Internet application keyboard navigation should behave like desktop application keyboard navigation. For example, keyboard users tab to Windows® Explorer and then use the arrow keys to navigate to elements in the tree. WAI-ARIA provides support for arrow key navigation of complex widgets, such as menus, trees and grids, via the tabindex attribute or activedescendant property. For more information on how to implement arrow key navigation, see WAI-ARIA Best Practices and Keyboard navigable JavaScript widgets (links reside outside of ibm.com).

    For additional information, refer to the WCAG 2.0 examples for using both keyboard and other device-specific functions (link resides outside of ibm.com).

    Note for iOS platform: For keyboards connected to iOS devices, tab and arrow key navigation is not supported as described in the previous paragraph. Apple has its own set of proprietary keyboard navigation keys which are documented in the Apple Wireless Keyboard/VoiceOver help.

    Required unit tests for Script development technique 1

    Perform the following unit tests using a Web syntax analysis tool or a screen reader.

  2. JavaScript actions: Make JavaScript actions keyboard accessible.

    To comply with this technique, you must implement all of the following examples.

    Script example 3

    Typically, only links and form controls are in the keyboard tab order. However, complex widgets, such as trees, menus and grids, should also receive focus via tabbing and arrow key navigation should be supported for navigating elements within these widgets. For more information on how to implement arrow key navigation for complex widgets, see WAI-ARIA Best Practices and Keyboard navigable JavaScript widgets (links reside outside of ibm.com).

    In addition, browsers will sometimes map the pressing of the keyboard Enter key to mouse events. Therefore, device-dependent event triggers must be tested to determine if the browser simulates the event with the keyboard as a redundant input mechanism. If it does, then specifying the mouse event is sufficient. Two events might cause a problem when only one is expected. For example, onKeyDown should not be specified with onMouseDown because doing so will cause two browser events: one for the onKeyDown event because the user pressed down the Enter key and a simulated mouse click provided by the browser for onMouseDown.

    If the browser does not simulate the mouse event when the keyboard is used, then the keyboard event must also be specified.

    OnClick is an example of an event handler that sometimes behaves as a device-independent handler and in other cases as a device-dependent handler. Specifying the event handler OnClick on a link or form element should cause the browser to evoke the event if either the mouse or the Enter key is used to select it. In this case, OnClick acts in a device-independent manner, and is therefore directly accessible because the same action takes place when the link is clicked or the enter key is pressed. In other words, for a link that uses OnClick, if tabbing to a link and pressing the Enter key will cause the OnClick event to occur, then the script functionality can be operated via the keyboard without requiring the developer to code the second redundant onKeyPress event for the same element.

    The example below uses OnClick as a device-independent link, which is executed when the Enter Key is used to select the element:

    View this device-independent OnClick example

    The code for the example is as follows:

    <a href="webscripts.html#postexample" onclick="return confirm('Clicking OK will take you to the next paragraph');">View this device-independent onClick example</a>

    When the OnClick event is used with elements that are not links or form controls, OnClick is device-dependent, therefore you must provide a redundant device-independent event handler (onKeyPress) or an equivalent alternative. In order to gain focus on the text, you will need to implement the tabindex attribute. Once that is done, you can use the onKeyPress event handler to provide an alternative to OnClick.

    The example of code below presents a <div> element with a tabindex=0 to make it focusable. In order to make user input is device-independent, the <div> element contains both the OnClick and onKeyPress event handlers. The OnClick and onKeyPress event handlers enable mouse and keyboard-only users to operate the widget.

    <div id="widget_id" tabindex="0" onClick="return confirm('Clicking OK will take you to the next paragraph');" onKeyPress="return confirm('Clicking OK will take you to the next paragraph');"></div>

    Note that complex widgets, such as trees, menus and grids, have a different navigation paradigm. Complex widgets should receive focus via tabbing and arrow key navigation should be supported for navigating elements within the widgets. For more information on how to implement arrow key navigation for complex widgets, see WAI-ARIA Best Practices and Keyboard-navigable custom JavaScript widgets (links reside outside of ibm.com).

    Script example 4

    Do not write event handlers that use double-clicking (onDblClick).

    There is no keyboard equivalent specified in HTML 4.01. Instead, use one of the keyboard accessible handlers.

    Script example 5

    Do not write event handlers that rely on mouse coordinates. There is no keyboard-equivalent way to perform this function. An example of a script that relies on mouse coordinates is a server-side image map, which uses javascript:onmouseover as a precursor to performing an action.

    Script example 6

    Do not use scripts to remove focus when focus is received. The system focus indicator is an important part of accessibility for keyboard users. When focus is removed from a control via script on content that normally receives focus when the content is accessed can interfere with the focus cycle and prohibit a user's ability to interact with the control using the keyboard.

    The following example is a failure of this checkpoint:

    <input type="submit" onFocus="this.blur();">

    Required unit tests for Script development technique 2

    Perform the following unit tests using a Web syntax analysis tool or a screen reader.

  3. Information available: Ensure that information exposed or changed via scripting is available to assistive technologies.

    To comply with this technique, you must implement all of the following examples.

    Script example 7

    Assume that a blind user is completing a form, but forgets to enter a required phone number. JavaScript prevents the form from being submitted and renders an error message below the form indicating that a phone number is required.

    phone number field with asterisk indicating a required field

    The error message is created in the DOM, but unfortunately screen readers don’t always read elements created in the DOM, so a blind user doesn’t know that an error has occurred.
    This problem may be overcome by assigning an alert role to the message container as follows:

        function showErrorMsg(msg){
            var msgContainer = document.createElement('div');
            msgContainer.setAttribute('role', 'alert');
            msgContainer.setAttribute('id', 'alert');

            var msg = document.createTextNode(msg);
            msgContainer.appendChild(msg);

            document.body.appendChild(msgContainer);
        }

    When an error occurs, the JavaScript function creates a <div> element and assigns it a role of alert. A text node containing the error message is created and appended to the <div> element. Finally, the <div> is appended to the document body. The alert role causes a screen reader to read the error message when it is rendered.

    Also, see the Dojo examples in Checkpoint 3.3a: Error Identification for information about providing a text message that identifies a field as mandatory or a text message that indicates when user input falls outside the required format or values.

    Script example 8

    When using document.write, the content should be written to the same page or the user must be notified if document.write creates content in new page/window and then focus must be set to the new window.

    Required unit tests for Script development technique 3

    Perform the following unit tests using a Web syntax analysis tool or a screen reader.


Recommended development techniques

Although you do not have to implement the recommended techniques in order to comply with this checkpoint, you should review them because they can improve the accessibility and usability of the application.

Refer to the WCAG 2.0 Additional Techniques (Advisory) for Success Criterion 2.1.1 (link resides outside of ibm.com) for a list of keyboard-related techniques and examples.

The recommended development techniques for this checkpoint are as follows:

  1. Don't use scripts that constantly refresh visible content.
  2. Inform the user that the page will be reloaded when a specific action/event is taken, what will be changed, and how to get back to where they where. For example, if by selecting a menu item, a second select menu item is changed by reloading the page, the user needs to know that before selecting the first menu item. If a skip link is provided to quickly navigate to the changed content, then the users can efficiently change and navigate the content. Examples of this technique are under development.
  3. Review placement of content in document order. Examples of this technique are under development.
  4. When content is added, (>3 items) update the tab order if needed. Examples of this technique are under development.
  5. When possible, content that is modified should be AFTER the current cursor location. Examples of this technique are under development.
  6. Do not turn off scroll bars. Examples of this technique are under development.

Recommended development example 1

Scripts that change content continuously, such as a real-time clock, create accessibility problems for assistive technologies. Try not to use any scripts that constantly refresh visible content. Rather, give the user the option of pressing a device-independent button that will display the "refreshed" content only when the button is pressed. The clock example below uses a global script to continually update a hidden element with the correct time. When a user clicks the "Display current time" button, the time is then shown on the screen in a dialog box.

The code for the above example is as follows:

<form action=""> <input type="hidden" id="face" size="13" value="" /> <input type="button" value="Display the current time" onclick="alert('The current time is ' + document.getElementById('face').value);" />

With the advent of WAI-ARIA live regions, Web application developers can easily make dynamic content accessible to screen reader users. However, when live region information is auto-updating, a mechanism must be provided to stop and restart the flow of information so as not to overwhelm a screen reader user. For example, the following stock ticker widget provides a Pause ticker checkbox that allows the user to pause the flow of stock quotes displayed by the ticker.

Start stock ticker. Pause ticker. Stock Quotes.

The HTML code that is used to render the ticker is as follows. The aria-live attribute on the <fieldset> element.enables a screen reader to announce quotes as they appear in the ticker.

<input type="button" id="startQuotes" name="startQuotes" value="Start stock ticker" onclick="showQuotes();"> <input type="checkbox" id="tickerOff" name="tickerOff" onclick="toggleTicker(this)"> <label for="startQuotes">Pause ticker</label> <fieldset id="quote" aria-live="polite"><legend>Stock Quotes</legend></fieldset>

The showQuote() function starts the flow of quotes into the ticker box. When the Pause ticker checkbox is checked, toggleTicker() is called, which stops the flow of quotes. When the checkbox is unchecked, the ticker resumes displaying quotes.

<script type="text/javascript">
var t;

/* Start quotes */
function showQuotes(){

/* Simulate a stock ticker */
    var quotes = new Array("IBM 97.75", "GLW 7.87", "C 8.75", "WB 5.98",
"SUN 3.65", "RIG 72.25");

var quoteStr =
document.createTextNode(quotes[Math.floor(Math.random()*6)]);
var msgContainer = document.createElement('div');
    msgContainer.appendChild(quoteStr);

    document.getElementById('quote').appendChild(msgContainer);

    /* Show a quote every second */
    t=setTimeout("showQuotes()",1000);

}

/* Pause/resume quotes */
function toggleTicker(obj){
    if (obj.checked == true){
      clearTimeout(t);
    } else {
      showQuote();
    }
} </script>

For more information on WAI-ARIA live regions, see the WAI-ARIA specification and WAI-ARIA Best Practices (links reside outside of ibm.com).


©2013 IBM Corporation

Last updated January 1, 2013.

W3C Recommendation 11 December 2008: http://www.w3.org/TR/WCAG20/ (link resides outside of ibm.com)
Copyright 1994-2009 W3C (Massachusetts Institute of Technology, European Research Consortium for Informatics and Mathematics, Keio University), All Rights Reserved.