repo_id
stringlengths
22
103
file_path
stringlengths
41
147
content
stringlengths
181
193k
__index_level_0__
int64
0
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/tree_role/index.md
--- title: "ARIA: tree role" slug: Web/Accessibility/ARIA/Roles/tree_role page-type: aria-role spec-urls: - https://w3c.github.io/aria/#tree - https://www.w3.org/WAI/ARIA/apg/patterns/treeview/examples/treeview-navigation/ --- A `tree` is a widget that allows the user to select one or more items from a hierarchically organized collection. ## Description A `tree` widget is a hierarchical list with parent and child nodes that can expand and collapse. Any item in the hierarchy may have child tree items, set with [`role="treeitem"`](/en-US/docs/Web/Accessibility/ARIA/Roles/treeitem_role). Tree items that have children can be expanded or collapsed, showing and hiding their children. An example of a `tree` is a file system selection user interface: a tree view displaying folders and files. Folder items can be expanded to reveal the contents of the folder — which may be files, folders, or both — and collapsed, hiding its contents. ARIA tree views are navigated primarily with arrow keys on the keyboard instead of the <kbd>Tab</kbd>. This form of navigation is not common for most browser content, though normal and expected for native applications. For this reason, before creating a tree view, consider alternative options to address the functionality you need. > **Warning:** Tree views use navigation more similar to native applications than to web applications. For this reason, consider alternative options to address the functionality you need before creating a tree view. ### Single and multiple select trees Trees can be "single-select", allowing users to choose just one item for an action, or "multi-select", where users are able to select more than one item for an action. In multi-select trees, the `tree` has [`aria-multiselectable`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-multiselectable) set to true. Otherwise, `aria-multiselectable` is either set to `false` or the default value of `false` is implied. In both cases, to be keyboard accessible, focus must be managed for all tree descendants. In some implementations of single-select tree, the focused item also has a selected state; this is known as "selection follows focus". When a single-select tree receives focus, if none of the tree items are selected before the tree receives focus, focus is set on the first node. If a tree item is selected before the tree receives focus, focus is set on the selected tree item. In single-select trees, [`aria-selected`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-selected) is set to `true` for the selected tree items and it is not present on any other tree item in the tree. In multi-select trees, all selected tree items have `aria-selected="true"` set and all tree item nodes that are selectable but not currently selected have `aria-selected="false"` set. Do not includes the `aria-selected` attribute on tree items that are not selectable. When a multi-select tree receives focus, if none of the tree items are selected before the tree receives focus, focus is set on the first tree item. If one or more tree items are selected before the tree receives focus, focus is set on the first selected node. In multi-select trees, the selected state is always independent of the focus. For example, in a typical file system navigator, the user can move focus to select any number of files for an action, such as copy or move. The visual design should make it clear which items are selected and which item has focus. ### Tree hierarchy In a tree view, the `tree` node is the root node; it can have child, grandchild, and further descendant `treeitem` nodes. Each element serving as a tree node has role `treeitem`, except for the root tree node which has a role of `tree`. A `tree` does not have a parent `tree` node - it is the root node. If a node is both nested in a tree and has descendant tree items, then it has the role `treeitem` and the [`aria-expanded`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-expanded) attribute; `aria-expanded="false"` is set when the node is in a closed state, `aria-expanded="true"` is set when the node is in an open state. `treeitem` nodes can be direct children of the `tree` root node, nested within a `treeitem` node, or, optionally nested in a [`group`](/en-US/docs/Web/Accessibility/ARIA/Roles/group_role) element, which, when nested in a `tree` is an expandable collections of treeitem elements. Do not include `aria-expanded` on end nodes — those without tree item children — as that would incorrectly describe the node as a parent node to assistive technologies. ### DOM placement and presence All treeitems are contained in or owned by an element with role `tree`. If there are any tree items that are not direct descendants of the `tree` in the markup, include [`aria-owns`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-owns) on the owning tree container to include elements that are not DOM children of the container. These non-child owned elements will appear in the reading order in the sequence they are referenced and after any tree items that are DOM children. Scripts that manage focus need to ensure the visual focus order matches this assistive technology reading order. If the complete set of available nodes is not present in the DOM due to dynamic loading as the user moves focus in or scrolls the tree, each node has [`aria-level`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-level), [`aria-setsize`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-setsize), and [`aria-posinset`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-posinset) specified. ### Accessible name The `tree` must be provided with an accessible name. Either reference a visible label referenced with [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) or specify a label with [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label). ### Menu orientation Elements with the role `tree` have an implicit [`aria-orientation`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-orientation) value of vertical. If the tree element is horizontally oriented, include `aria-orientation="horizontal"`. ### Associated WAI-ARIA roles, states, and properties - [`role="treeitem"`](/en-US/docs/Web/Accessibility/ARIA/Roles/treeitem_role) - : An item in a tree. - [`role="group"`](/en-US/docs/Web/Accessibility/ARIA/Roles/group_role) - : An expandable collection of tree items. - [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) - : Identifies the element (or elements) that labels the `tree` providing the required accessible name when a visible label is present. Otherwise use `aria-label`. - [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) - : Defines a string value that labels the `tree` when no visible label is present. - [`aria-orientation`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-orientation) - : indicates whether the tree orientation is horizontal or vertical; defaults to `vertical` if omitted. - [`aria-multiselectable`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-multiselectable) - : When set to true, indicates the user may select more than one tree item from the tree's current selectable descendants. ### Keyboard interactions For a vertically oriented `tree`, which is the default orientation: <table> <tr> <td><kbd>Right arrow</kbd></td> <td> <ul> <li>When focus is on a closed node, opens the node; focus does not move. <li>When focus is on an open node, moves focus to the first child node. <li>When focus is on an end node (a tree item with no children), does nothing. </td> </tr> <tr> <td><kbd>Left arrow</kbd></td> <td> <ul> <li>When focus is on an open node, closes the node. <li>When focus is on a child node that is also either an end node or a closed node, moves focus to its parent node. <li>When focus is on a closed `tree`, does nothing. </td> </tr> <tr> <td><kbd>Down Arrow</kbd></td> <td> Moves focus to the next node that is focusable without opening or closing a node. </td> </tr> <tr> <td><kbd>Up Arrow</kbd></td> <td> Moves focus to the previous node that is focusable without opening or closing a node. </td> </tr> <tr> <td><kbd>Home</kbd></td> <td> Moves focus to the first node in the tree without opening or closing a node. </td> </tr> <tr> <td><kbd>End</kbd></td> <td> Moves focus to the last node in the tree that is focusable without opening the node. </td> </tr> <tr> <td><kbd>Enter</kbd></td> <td>Performs the default action of the currently focused node. For parent nodes, it opens or closes the node. In single-select trees, if the node has no children, selects the current node if not already selected (which is the default action). </td> </tr> <tr> <td>Type a character*</td> <td> <ul> <li>Focus moves to the next node with a name that starts with the typed character. <li>If multiple characters are typed in rapid succession, focus moves to the next node with a name that starts with the string of characters typed. </td> </tr> <tr> <td> <kbd>*</kbd> (Optional)</td> <td> Expands all siblings that are at the same level as the current node. </td> </tr> </table> \* Type-ahead is recommended for all trees, especially for trees with more than 7 root nodes ### Multi-select keyboard interactions There are two interaction models for multi-select trees: While you can require that users press a modifier key, such as <kbd>Shift</kbd> or <kbd>Control</kbd> while navigating the list in order to avoid losing selection states, the model that does not require the user to hold a modifier key is recommended. #### Recommended multi user select model <table> <tr> <td><kbd>Space</kbd></td> <td> Toggles the selection state of the focused node. </td> </tr> <tr> <td><kbd>Shift + Down Arrow</kbd> (Optional)</td> <td> Moves focus to and toggles the selection state of the next node. </td> </tr> <tr> <td><kbd>Shift + Up Arrow</kbd> (Optional)</td> <td> Moves focus to and toggles the selection state of the previous node. </td> </tr> <tr> <td><kbd>Shift + Space</kbd> (Optional)</td> <td> Selects contiguous nodes from the most recently selected node to the current node. </td> </tr> <tr> <td><kbd>Control + Shift + Home</kbd> (Optional)</td> <td> Selects the node with focus and all nodes up to the first node. Optionally, moves focus to the first node. </td> </tr> <tr> <td><kbd>Control + Shift + End</kbd> (Optional)</td> <td> Selects the node with focus and all nodes down to the last node. Optionally, moves focus to the last node. </td> </tr> <tr> <td><kbd>Control + A</kbd> (Optional)</td> <td> Selects all nodes in the tree. Optionally, if all nodes are selected, it can also unselect all nodes.</td> </tr> </table> #### Alternative multi-selection model The alternative multi-selection model is a modifier key model in which moving focus without holding a modifier key such as <kbd>Shift</kbd> or <kbd>Control</kbd> unselects all selected nodes except for the focused node: <table> <tr> <td><kbd>Shift + Down Arrow</kbd></td> <td> Moves focus to and toggles the selection state of the next node. </td> </tr> <tr> <td><kbd>Shift + Up Arrow</kbd></td> <td> Moves focus to and toggles the selection state of the previous node. </td> </tr> <tr> <td><kbd>Control + Down Arrow</kbd></td> <td> Without changing the selection state, moves focus to the next node. </td> </tr> <tr> <td><kbd>Control + Up Arrow</kbd></td> <td> Without changing the selection state, moves focus to the previous node. </td> </tr> <tr> <td><kbd>Control + Space</kbd></td> <td> Toggles the selection state of the focused node. </td> </tr> <tr> <td><kbd>Shift + Space</kbd> (Optional)</td> <td> Selects contiguous nodes from the most recently selected node to the current node. </td> </tr> <tr> <td><kbd>Control + Shift + Home</kbd> (Optional)</td> <td> Selects the node with focus and all nodes up to the first node. Optionally, moves focus to the first node. </td> </tr> <tr> <td><kbd>Control + Shift + End</kbd> (Optional)</td> <td> Selects the node with focus and all nodes down to the last node. Optionally, moves focus to the last node. </td> </tr> <tr> <td><kbd>Control + A</kbd> (Optional)</td> <td> Selects all nodes in the tree. Optionally, if all nodes are selected, it can also unselect all nodes. </td> </tr> </table> ## Specifications {{Specifications}} ## See also <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/article_role/index.md
--- title: "ARIA: article role" slug: Web/Accessibility/ARIA/Roles/article_role page-type: aria-role spec-urls: - https://w3c.github.io/aria/#article - https://www.w3.org/WAI/ARIA/apg/patterns/feed/examples/feed/ --- The `article` role indicates a section of a page that could easily stand on its own on a page, in a document, or on a website. It is usually set on related content items such as comments, forum posts, newspaper articles or other items grouped together on one page. ```html <div role="article"> <h2>Heading of the segment</h2> <p>Paragraph for the segment.</p> <p>Another paragraph.</p> Controls to interact with the article, share it, etc. </div> <div role="article">…</div> ``` This example shows two articles side by side on one page that could be structured similarly and are related. > **Note:** Instead of a `<div>` with an `article` role, use the {{HTMLElement('article')}} element. **Always use native element if available** Don't use `role="article"`. Instead use the `<article>` element. ```html <article> <h2>Heading of the segment</h2> <p>Paragraph for the segment.</p> <p>Another paragraph.</p> Controls to interact with the article, share it, etc. </article> <article>…</article> ``` ## Description The `article` [document structure role](/en-US/docs/Web/Accessibility/ARIA/Roles#1._document_structure_roles) denotes a section of a document, page, or site that, if it were standing on its own, could be viewed as a complete document, page or site. The aim of a set of article sections is to indicate their relationship to one another. Articles are not considered a navigational landmark, but many assistive technologies that support landmarks also support a means to navigate among articles. They may also support indication of nesting relationships within articles. Articles can be nested, indicating that a nested article directly relates to the one it is nested in, but not necessarily to the ones outside the nesting hierarchy. Reference the examples for specific use cases. If an article is part of a feed, it can have the [`aria-posinset`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-posinset) and [`aria-setsize`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-setsize) attributes set to indicate which position within the feed this particular article represents. Inside an `application` or other widget that causes screen readers and other assistive technologies to be in pass-through mode, an article can be used to indicate that these should switch back to treating the enclosed content as regular web content. Instead of including the `article` role on a non-semantic element, the {{HTMLElement('article')}} element should be used. User agents translate this to the appropriate accessibility information just like the `article` role. Using the {{HTMLElement('article')}} element also helps search engines better discover the structure of a page. Examples of appropriate uses of the `role="article"`, or preferably `<article>`, include blog posts, forum posts, a comment to a forum or blog post, any an item in a social media feed. ### Associated WAI-ARIA roles, states, and properties - [`aria-posinset`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-posinset) - : In the context of a feed, indicates the position of this particular article within that feed, based on a count starting at 1. - [`aria-setsize`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-setsize) - : In the context of a feed, indicates how many article items there are within that feed. ### Keyboard interactions This role does not support any specific keyboard interaction. ### Required JavaScript features - Event handlers - : This role does not require any event handlers to be present. - Changing attribute values - : When constructing a feed, set the `aria-posinset` and `aria-setsize` attributes on each article role to the appropriate values, bearing in mind that `aria-posinset` is 1-based. > **Note:** **Always use native element if available.** Instead of a `<div>` with the `article` role, the `<article>` element should be used. ## Examples - The [restaurant recommendations feed display](https://www.w3.org/WAI/ARIA/apg/patterns/feed/examples/feed-display.html) along with its separate [documentation](https://www.w3.org/WAI/ARIA/apg/patterns/feed/examples/feed/) from the WAI-ARIA 1.1 authoring practices feed design pattern ## Specifications {{Specifications}} ## Precedence order This role corresponds to the {{HTMLElement('article')}} element in HTML, and that element should be used instead, if possible. This role does not require any specific roles to be present among its children. It is the only role allowed as a direct child of an element with the [`feed`](/en-US/docs/Web/Accessibility/ARIA/Roles/feed_role) role. ## See also - [`feed` role](/en-US/docs/Web/Accessibility/ARIA/Roles/feed_role) - [`section` role](/en-US/docs/Web/Accessibility/ARIA/Roles/section_role) - The {{HTMLElement('article')}} element - {{Glossary("RSS")}} glossary definition <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/checkbox_role/index.md
--- title: "ARIA: checkbox role" slug: Web/Accessibility/ARIA/Roles/checkbox_role page-type: aria-role --- The `checkbox` role is for checkable interactive controls. Elements containing `role="checkbox"` must also include the [`aria-checked`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked) attribute to expose the checkbox's state to assistive technology. ```html <span role="checkbox" aria-checked="false" tabindex="0" aria-labelledby="chk1-label"></span> <label id="chk1-label">Remember my preferences</label> ``` > **Note:** The first rule of ARIA is if a native HTML element or attribute has the semantics and behavior you require, use it instead of re-purposing an element and adding ARIA. Instead use the native [HTML checkbox of `<input type="checkbox">`](/en-US/docs/Web/HTML/Element/input/checkbox) (with an associated {{HTMLElement('label')}}), which natively provides all the functionality required: ```html <input type="checkbox" id="chk1-label" name="RememberPreferences" /> <label for="chk1-label">Remember my preferences</label> ``` ## Description The native HTML checkbox ([`<input type="checkbox">`](/en-US/docs/Web/HTML/Element/input/checkbox)) form control had two states ("checked" or "not checked"), with an [`indeterminate`](/en-US/docs/Web/HTML/Element/input/checkbox#indeterminate_state_checkboxes) state settable via JavaScript. Similarly, an element with `role="checkbox"` can expose three states through the `aria-checked` attribute: `true`, `false`, or `mixed`. Since a checkbox is an interactive control, it must be focusable and keyboard accessible. If the role is applied to a non-focusable element, use the [`tabindex`](/en-US/docs/Web/HTML/Global_attributes/tabindex) attribute to change this. The expected keyboard shortcut for activating a checkbox is the <kbd>Space</kbd> key. The developer is required to change the value of the `aria-checked` attribute dynamically when the checkbox is activated. ### All descendants are presentational There are some types of user interface components that, when represented in a platform accessibility API, can only contain text. Accessibility APIs do not have a way of representing semantic elements contained in a `checkbox`. To deal with this limitation, browsers, automatically apply role [`presentation`](/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role) to all descendant elements of any `checkbox` element as it is a role that does not support semantic children. For example, consider the following `checkbox` element, which contains a heading. ```html <div role="checkbox"><h6>Name of my checkbox</h6></div> ``` Because descendants of `checkbox` are presentational, the following code is equivalent: ```html <div role="checkbox"><h6 role="presentation">Name of my checkbox</h6></div> ``` From the assistive technology user's perspective, the heading does not exist since the previous code snippets are equivalent to the following in the [accessibility tree](/en-US/docs/Glossary/Accessibility_tree): ```html <div role="checkbox">Name of my checkbox</div> ``` ### Associated WAI-ARIA Roles, States, and Properties - [`aria-checked`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked) - : The value of `aria-checked` defines the state of a checkbox. This attribute has one of three possible values: - `true` - : The checkbox is checked. - `false` - : The checkbox is not checked. - `mixed` - : The checkbox is partially checked, or indeterminate. - `tabindex="0"` - : Used to make it focusable so the assistive technology user can tab to it and start reading right away. ### Keyboard interactions | Key | Function | | ---------------- | ---------------------- | | <kbd>Space</kbd> | Activates the checkbox | ### Required JavaScript #### Required event handlers - `onclick` - : Handle mouse clicks on both the checkbox and the associated label that will change the state of the checkbox by changing the value of the `aria-checked` attribute and the appearance of the checkbox so it appears checked or unchecked to the sighted user - `onKeyDown` - : Handle the case where the user presses the <kbd>Space</kbd> key to change the state of the checkbox by changing the value of the `aria-checked` attribute and the appearance of the checkbox so it appears checked or unchecked to the sighted user ## Examples The following example creates an otherwise non-semantic checkbox element using CSS and JavaScript to handle the checked or unchecked status of the element. ### HTML ```html <span role="checkbox" id="chkPref" aria-checked="false" onclick="changeCheckbox()" onKeyDown="changeCheckbox(event.keyCode)" tabindex="0" aria-labelledby="chk1-label"></span> <label id="chk1-label" onclick="changeCheckbox()" onKeyDown="changeCheckbox(event.keyCode)" >Remember my preferences</label > ``` ### CSS ```css [role="checkbox"] { padding: 5px; } [role="checkbox"]:focus { border: 2px solid #0198e1; } [aria-checked="true"]::before { content: "[x]"; } [aria-checked="false"]::before { content: "[ ]"; } ``` ### JavaScript ```js function changeCheckbox(keyCode) { const spacebarKeyCode = 32; const item = document.getElementById("chkPref"); const checked = item.getAttribute("aria-checked"); if (keyCode && keyCode !== spacebarKeyCode) { return; } else if (checked === "true") { item.setAttribute("aria-checked", "false"); } else { item.setAttribute("aria-checked", "true"); } } ``` {{EmbedLiveSample("Examples", 230, 250)}} ## Accessibility concerns When the `checkbox` role is added to an element, the user agent should do the following: - Expose the element as having a `checkbox` role in the operating system's accessibility API. - When the `aria-checked` value changes, send an accessible state changed event. Assistive technology products should do the following: - Screen readers should announce the element as a checkbox, and optionally provide instructions on how to activate it. People implementing checkboxes should do the following: - Ensure that the checkbox can be reached and interacted with by both keyboard controls and clicks - Keep the `aria-checked` attribute up to date following user interactions - Provide styles that indicate when the checkbox has focus > **Note:** Opinions may differ on how assistive technology should handle this technique. The information provided above is one of those opinions and may change. ## Best practices The first rule of ARIA is: if a native HTML element or attribute has the semantics and behavior you require, use it instead of re-purposing an element and adding an ARIA role, state or property to make it accessible. As such, it is recommended to use the native [HTML checkbox](/en-US/docs/Web/HTML/Element/input/checkbox) using form control instead of recreating a checkbox's functionality with JavaScript and ARIA. ## See also - [`<input type="checkbox">`](/en-US/docs/Web/HTML/Element/input/checkbox) - [ARIA: `radio` role](/en-US/docs/Web/Accessibility/ARIA/Roles/radio_role) - [ARIA: `menuitem` role](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitem_role) - [ARIA: `menuitemcheckbox` role](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemcheckbox_role) - [ARIA: `menuitemradio` role](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemradio_role) - [ARIA: `switch` role](/en-US/docs/Web/Accessibility/ARIA/Roles/switch_role) - [ARIA: `option` role](/en-US/docs/Web/Accessibility/ARIA/Roles/option_role) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/definition_role/index.md
--- title: "ARIA: definition role" slug: Web/Accessibility/ARIA/Roles/definition_role page-type: aria-role spec-urls: https://w3c.github.io/aria/#definition --- The `definition` ARIA role indicates the element is a definition of a term or concept. ## Description The `definition` ARIA role can be included on an element that is a definition of a term or concept, similar to the native {{HTMLElement('dfn')}} element. To associate the definition with the `term` being defined, and to provide an accessible name, reference the term being defined with `role="term"`, using [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby). ```html-nolint <p> <span role="term">Mansplaining</span>, <span role="definition"> a portmanteau of "man" and "explain", is the patronizing act of explaining without being asked to do so, to someone already learned on the topic, often after someone has already explained it </span>. </p> ``` > **Note:** Instead of a `<span>` with the [`term`](/en-US/docs/Web/Accessibility/ARIA/Roles/term_role) and `definition` roles, use the {{HTMLElement('dfn')}} element. **Always use native element if available.** ```html <p> <dfn>Mansplaining</dfn>, a portmanteau of "man" and "explain", is the patronizing act of explaining without being asked to do so, to someone already learned on the topic, often after someone has already explained it. </p> ``` ## Specifications {{Specifications}} ## See also - [The `term` role](/en-US/docs/Web/Accessibility/ARIA/Roles/term_role) - The {{HTMLElement('dfn')}} element - The {{HTMLElement('dd')}} element - The {{HTMLElement('dl')}} element - The {{HTMLElement('dt')}} element <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/radio_role/index.md
--- title: "ARIA: radio role" slug: Web/Accessibility/ARIA/Roles/radio_role page-type: aria-role --- The `radio` role is one of a group of checkable radio buttons, in a `radiogroup`, where no more than a single radio button can be checked at a time. ## Description A radio button is a checkable input that when associated with other radio buttons, only one of which can be checked at a time. The radio buttons must be grouped together in a [`radiogroup`](/en-US/docs/Web/Accessibility/ARIA/Roles/radiogroup_role) to indicate which ones affect the same value. ```html <div role="radiogroup" aria-labelledby="legend25" id="radiogroup25"> <p id="legend25">Ipsum and lorem?</p> <div> <span role="radio" aria-checked="false" tabindex="0" aria-labelledby="q25_radio1-label" data-value="True"></span> <label id="q25_radio1-label">True</label> </div> <div> <span role="radio" aria-checked="false" tabindex="0" aria-labelledby="q25_radio2-label" data-value="False"></span> <label id="q25_radio2-label">False</label> </div> <div> <span role="radio" aria-checked="true" tabindex="0" aria-labelledby="q25_radio3-label" data-value="huh?"></span> <label id="q25_radio3-label">What is the question?</label> </div> </div> ``` The `role` attribute only adds semantics; all of the functionality that comes natively with the [HTML radio](/en-US/docs/Web/HTML/Element/input/radio) needs to be added with JavaScript and the HTML [`tabindex`](/en-US/docs/Web/HTML/Global_attributes/tabindex) attribute. > **Note:** The first rule of ARIA is if a native HTML element or attribute has the semantics and behavior you require, use it instead of re-purposing an element and adding ARIA. Instead use the native [HTML `<input type="radio">`](/en-US/docs/Web/HTML/Element/input/radio) (with an associated {{HTMLElement('label')}}, which natively provides all the functionality required: ```html <fieldset> <legend>Ipsum and lorem?</legend> <div> <input type="radio" value="True" id="q25_radio1" name="q25" /> <label for="q25_radio1">True</label> </div> <div> <input type="radio" value="False" id="q25_radio2" name="q25" /> <label for="q25_radio2">False</label> </div> <div> <input type="radio" value="huh?" id="q25_radio3" name="q25" checked /> <label for="q25_radio3">What is the question?</label> </div> </fieldset> ``` The native HTML radio form control ([`<input type="radio">`](/en-US/docs/Web/HTML/Element/input/radio)) has two states ("checked" or "not checked"). Similarly, an element with `role="radio"` can expose two states through the [`aria-checked`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked) attribute: `true` representing the checked state, and `false` representing the unchecked state. The `aria-checked` value of `mixed` is not valid to use for a radio button. If a radio button is checked, the radio element has `aria-checked` set to `true`. If it is not checked, it has `aria-checked` set to `false`. Each radio button element has role `radio`. The radio role should always be nested with other associated radios in a `radiogroup`. If it is not possible to nest the radio button within a radio group, use the `id` of the non-grouped radio in a space separated list of values as the value of the [`aria-owns`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-owns) attribute on the `radiogroup` element to indicate the relationship of the `radiogroup` to its radio members. Each radio element is labelled by its content, has a visible label referenced by `aria-labelledby`, or has a label specified with `aria-label`. The containing `radiogroup` element should either have a visible label referenced by `aria-labelledby` or a label specified with `aria-label`. If elements providing additional information about either the radio group or each radio button are present, those elements should be referenced by the `radiogroup` element or radio elements with the [`aria-describedby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby) property. As `radio` is an interactive control; it must be focusable and keyboard accessible. If the role is applied to a non-focusable element, use the [`tabindex`](/en-US/docs/Web/HTML/Global_attributes/tabindex) attribute to change this. The expected keyboard shortcut for activating a radio is the <kbd>Space</kbd> key. Use JavaScript to toggle the `aria-checked` attribute to `true` when a radio becomes checked while ensuing that all the other radio roles in the group are set to `aria-checked="false"`. To programmatically indicate that a radio button must be chosen from a radio group the [`aria-required`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-required) attribute, with a value of `true`, must be specified on the `radiogroup` element. It is not expected to use the `aria-required` attribute on individual ARIA radio buttons. ### All descendants are presentational There are some types of user interface components that, when represented in a platform accessibility API, can only contain text. Accessibility APIs do not have a way of representing semantic elements contained in a `radio`. To deal with this limitation, browsers, automatically apply role [`presentation`](/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role) to all descendant elements of any `radio` element as it is a role that does not support semantic children. For example, consider the following `radio` element, which contains a heading. ```html <div role="radio"><h6>name of my radio</h6></div> ``` Because descendants of `radio` are presentational, the following code is equivalent: ```html <div role="radio"><h6 role="presentation">name of my radio</h6></div> ``` From the assistive technology user's perspective, the heading does not exist since the previous code snippets are equivalent to the following in the [accessibility tree](/en-US/docs/Glossary/Accessibility_tree): ```html <div role="radio">name of my radio</div> ``` ## Associated WAI-ARIA Roles, States, and Properties - [`radiogroup`](/en-US/docs/Web/Accessibility/ARIA/Roles/radiogroup_role) role - : The radio buttons are contained in or owned by an element with role `radiogroup`. If unable to be nested within a `radiogroup` within the markup, the `aria-owns` attribute of the `radiogroup` contains the `id` values of the non-nested radio buttons in the group. - [`aria-checked`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked) - : The value of `aria-checked` defines the state of a radio. When used with radio elements, the attribute has one of two possible values: - `true` - : The radio is checked. - `false` - : The radio is not checked. > **Note:** use the [`tabindex` attribute](/en-US/docs/Web/HTML/Global_attributes/tabindex) if the `role="radio"` is used on an element that does not natively accept keyboard focus. E.g., a `<div>` or `<span>`. ## Keyboard interactions - <kbd>Tab</kbd> + <kbd>Shift</kbd> - : Move focus into and out of the radio group. When focus moves into a radio group, and a radio button is already checked, focus is set on the checked button. If none of the radio buttons are checked, focus is set on the first radio button in the group. - <kbd>Space</kbd> - : Checks the radio if not already checked. Unchecks a previously checked radio button in the radio group. - <kbd>Right Arrow</kbd> and <kbd>Down Arrow</kbd> - : Move focus to and checks the next radio button in the group, unchecking the previously focused radio button. If focus is on the last radio button, focus moves to the first radio button. - <kbd>Left Arrow</kbd> and <kbd>Up Arrow</kbd> - : Move focus to and checks the previous radio button in the group, unchecking the previously focused radio button. If focus is on the first radio button, focus moves to the last radio button. ### Radios in a toolbar Because arrow keys are used to navigate among elements of a toolbar and the <kbd>Tab</kbd> key moves focus in and out of a toolbar, when a radio group is nested inside a toolbar, the keyboard interaction of the radio group is slightly different from that of a radio group that is not inside of a toolbar. See [`radiogroup` keyboard interactions](/en-US/docs/Web/Accessibility/ARIA/Roles/radiogroup_role#keyboard_interactions) for more information ## Required JavaScript - `onClick` - : Handle mouse clicks on both the radio and the associated label that will change the state of the radio by changing the value of the `aria-checked` attribute and the appearance of the radio so it appears checked or unchecked to the sighted user - `onKeyPress` - : Handle the case where the user presses the <kbd>Space</kbd> key to change the state of the radio by changing the value of the `aria-checked` attribute and the appearance of the radio so it appears checked or unchecked to the sighted user ## Examples The following example uses ARIA to modify otherwise generic elements to be exposed as radio buttons. CSS and JavaScript are used to visually and programmatically modify the checked or unchecked state of the element. ### HTML ```html <div role="radiogroup" aria-labelledby="legend" id="radiogroup"> <p id="legend"> Should you be using the <code>radio</code> role or <code>&lt;input type="radio"></code>? </p> <div> <span role="radio" aria-checked="true" tabindex="0" aria-labelledby="ariaLabel" data-value="True"></span> <label id="ariaLabel">ARIA role</label> </div> <div> <span role="radio" aria-checked="false" tabindex="0" aria-labelledby="htmllabel" data-value="False"></span> <label id="htmllabel">HTML <code>&lt;input type="radio"></code></label> </div> </div> ``` ### CSS ```css [role="radio"] { padding: 5px; } [role="radio"][aria-checked="true"]::before { content: "(x)"; font-family: monospace; } [role="radio"][aria-checked="false"]::before { content: "( )"; font-family: monospace; } ``` ### JavaScript A lot of JavaScript is required to make radio buttons out of non-semantic HTML. ```js // initialize all the radio role elements const radioGroups = document.querySelectorAll('[role="radiogroup"]'); for (let i = 0, groups = radioGroups.length; i < groups; i++) { const radios = radioGroups[i].querySelectorAll("[role=radio]"); for (let j = 0, radiobuttons = radios.length; j < radios; j++) { radios[j].addEventListener("keydown", function () { handleKeydown(); }); radios[j].addEventListener("click", function () { handleClick(); }); } } // handle mouse and touch events let handleClick = function (event) { setChecked(this); event.stopPropagation(); event.preventDefault(); }; // handle key presses let handleKeydown = function (event) { switch (event.keyCode) { case 32: // space case 12: // return currentChecked(); break; case 38: // up case 37: // left previousRadioChecked(); break; case 40: // down case 39: // right nextItemChecked(); break; default: break; } event.stopPropagation(); event.preventDefault(); }; // when a radio is selected, give it focus, set checked to true; // ensure all other radios in radio group are not checked setChecked = function () { // uncheck all the radios in group // iterated through all the radios in radio group // eachRadio.tabIndex = -1; // eachRadio.setAttribute('aria-checked', 'false'); // set the selected radio to checked // thisRadio.setAttribute('aria-checked', 'true'); // thisRadio.tabIndex = 0; // thisRadio.focus(); // set the value of the radioGroup to the value of the currently selected radio }; ``` <!-- {{EmbedLiveSample("Examples", 230, 250)}} --> No JavaScript (or even CSS) would be needed had we used semantic HTML element with the name of each radio button in a group of radio buttons being the same: ```html <fieldset> <legend> Should you be using the <code>radio</code> role or <code>&lt;input type="radio"></code>? </legend> <div> <input type="radio" name="bestPractices" id="ariaLabel" value="True" /> <label for="ariaLabel">ARIA role</label> </div> <div> <input type="radio" name="bestPractices" id="htmllabel" value="False" /> <label for="htmllabel">HTML <code>&lt;input type="radio"></code></label> </div> </fieldset> ``` ## Best practices The first rule of ARIA is: if a native HTML element or attribute has the semantics and behavior you require, use it instead of re-purposing an element and adding an ARIA role, state or property to make it accessible. As such, it is recommended to use native [HTML radio button](/en-US/docs/Web/HTML/Element/input/radio) form controls instead of recreating a radio's functionality with JavaScript and ARIA. ## See also - [HTML `<input type="radio">` radio button](/en-US/docs/Web/HTML/Element/input/radio) - [HTML `tabindex` attribute](/en-US/docs/Web/HTML/Global_attributes/tabindex) - [ARIA: `radiogroup` role](/en-US/docs/Web/Accessibility/ARIA/Roles/radiogroup_role) - [ARIA: `checkbox` role](/en-US/docs/Web/Accessibility/ARIA/Roles/checkbox_role) - [ARIA: `menuitem` role](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitem_role) - [ARIA: `menuitemradio` role](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemradio_role) - [ARIA: `menuitemradio` role](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemradio_role) - [ARIA: `option` role](/en-US/docs/Web/Accessibility/ARIA/Roles/option_role) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/menu_role/index.md
--- title: "ARIA: menu role" slug: Web/Accessibility/ARIA/Roles/menu_role page-type: aria-role spec-urls: - https://w3c.github.io/aria/#menu - https://www.w3.org/WAI/ARIA/apg/patterns/menubar/examples/menubar-navigation/ --- The `menu` role is a type of composite widget that offers a list of choices to the user. ## Description A `menu` generally represents a grouping of common actions or functions that the user can invoke. The `menu` role is appropriate when a list of menu items is presented in a manner similar to a menu on a desktop application. Submenus, also known as pop-up menus, also have the role `menu`. While the term "menu" is a generically used term to describe site navigation, the `menu` role is for a list of actions or functions that require complex functionality, such as composite widget focus management and first-character navigation A menu can be a permanently visible list of controls or a widget that can be made to open and close. A closed `menu` widget is usually opened, or made visible, by activating a menu button, choosing an item in a menu that opens a submenu, or by invoking a command, such as <kbd>Shift + F10</kbd> in Windows which opens a context specific menu. When a user activates a choice in a menu that has been opened, the menu usually closes. If the menu choice action invokes a submenu, the menu will remain open and the submenu is displayed. When a menu opens, keyboard focus is placed on the first menu item. To be keyboard accessible, you need to [manage focus](https://usability.yale.edu/web-accessibility/articles/focus-keyboard-operability) for all descendants: all menu items within the `menu` are focusable. The menu button which opens the menu and the menu items, rather than the menu itself, are the focusable elements. Menu items include [`menuitem`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitem_role), [`menuitemcheckbox`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemcheckbox_role), and [`menuitemradio`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemradio_role). [Disabled](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-disabled) menu items are focusable but cannot be activated. Menu items can be grouped in elements with the [`group`](/en-US/docs/Web/Accessibility/ARIA/Roles/group_role) role, and separated by elements with role [`separator`](/en-US/docs/Web/Accessibility/ARIA/Roles/separator_role). Neither `group` nor `separator` receive focus or are interactive. If a `menu` is opened as a result of a context action, <kbd>Escape</kbd> or <kbd>Enter</kbd> may return focus to the invoking context. If focus was on the menu button, <kbd>Enter</kbd> opens the menu, giving focus to the first menu item. If focus is on the menu itself, <kbd>Escape</kbd> closes the menu and returns focus to the menu button or parent menubar item (or the context action that opened the menu). Elements with the role `menu` have an implicit [`aria-orientation`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-orientation) value of `vertical`. For horizontally oriented menu, use [`aria-orientation="horizontal"`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-orientation). If the menu is visually persistent, consider the [`menubar`](/en-US/docs/Web/Accessibility/ARIA/Roles/menubar_role) role instead. ### Associated WAI-ARIA roles, states, and properties - [`menuitem`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitem_role), [`menuitemcheckbox`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemcheckbox_role), and [`menuitemradio`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemradio_role) roles - : Roles of items contained in a containing `menu` or `menubar`, known collectively as "menu items". These must be able to receive focus. - [`group`](/en-US/docs/Web/Accessibility/ARIA/Roles/group_role) role - : Menu items can be nested in a [`group`](/en-US/docs/Web/Accessibility/ARIA/Roles/group_role) - [`separator`](/en-US/docs/Web/Accessibility/ARIA/Roles/separator_role) role - : A divider that separates and distinguishes sections of content or groups of menu items within the menu - [`tabindex`](/en-US/docs/Web/HTML/Global_attributes#tabindex) attribute - : The `menu` container has `tabindex` set to `-1` or `0` and each item in the menu has `tabindex` set to `-1`. - [`aria-activedescendant`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-activedescendant) - : Set to the ID of the focused item, if there is one. - [`aria-orientation`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-orientation) - : indicates whether the menu orientation is horizontal or vertical; defaults to `vertical` if omitted. - [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) or [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) - : The `menu` is required to have an accessible name. Use `aria-labelledby` if a visible label is present, otherwise use `aria-label`. Either include the `aria-labelledby` set to a the `id` to the `menuitem` or `button` that controls its display or use `aria-label` to define the label. - [`aria-owns`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-owns) - : Only set on the menu container to include elements that are not DOM children of the container. If set, those elements will appear in the reading order in the sequence they are referenced and after any items that are DOM children. When managing focus, ensure the visual focus order matches this assistive technology reading order. ### Keyboard interactions - <kbd>Space</kbd> / <kbd>Enter</kbd> - : If the item is a parent menu item, it opens the submenu and moves focus to the first item in the submenu. Otherwise, activates the menu item, which loads new content and places focus on the heading that titles the content. - <kbd>Escape</kbd> - : When in a submenu, it closes the submenu and moves focus to the parent menu or menubar item. - <kbd>Right Arrow</kbd> - : In a menubar, moves focus to the next item in the menubar. If focus is on the last item, it moves focus to the first item. If in a submenu, if focus is on an item that does not have a submenu, it closes the submenu and moves focus to the next item in the menubar. Otherwise, it opens the submenu of the newly focused menubar item, keeping focus on that parent menubar item. If not in a menubar or submenu and not on a `menuitem` with a submenu, if focus is not the last focusable element in the menu, it optionally moves focus to the next focusable element. - <kbd>Left Arrow </kbd> - : Moves focus to the previous item in the menubar. If focus is on the first item, it moves focus to the last item. If in a submenu, it closes the submenu and moves focus to the parent menu item. If not in a menubar or submenu, if focus is not the first focusable element in the menu, it optionally moves focus to the last focusable element. - <kbd>Down Arrow</kbd> - : Opens submenu and moves focus to the first item in the submenu. - <kbd>Up Arrow</kbd> - : Opens submenu and moves focus to the last item in the submenu. - <kbd>Home</kbd> - : Moves focus to the first item in the menubar. - <kbd>End</kbd> - : Moves focus to the last item in the menubar. - Any character key - : Moves focus to the next item in the menubar having a name that starts with the typed character. If none of the items have a name starting with the typed character, focus does not move. ## Examples Below are two example menu implementations. ### Example 1: navigation menu ```html <div> <button id="menubutton" aria-haspopup="true" aria-controls="menu"> <img src="hamburger.svg" alt="Page Sections" /> </button> <ul id="menu" role="menu" aria-labelledby="menubutton"> <li role="presentation"> <a role="menuitem" href="#description">Description</a> </li> <li role="presentation"> <a role="menuitem" href="#associated_wai-aria_roles_states_and_properties"> Associated WAI-ARIA roles, states, and properties </a> </li> <li role="presentation"> <a role="menuitem" href="#keyboard_interactions"> Keyboard interactions </a> </li> <li role="presentation"> <a role="menuitem" href="#examples">Examples</a> </li> <li role="presentation"> <a role="menuitem" href="#specifications">Specifications</a> </li> <li role="presentation"> <a role="menuitem" href="#see_also">See Also</a> </li> </ul> </div> ``` To progressively enhance this navigation widget that is by default accessible, the class to hide the `menu` and the inclusion of `tabindex="-1"` on the interactive menuitem content should be added with JavaScript on load. When including a "menu" for site navigation, do not use the `menu` role. Rather, for the main site navigation use the native HTML {{HTMLElement('nav')}} element or simply a list of links. The `menu` role should be reserved for composite widgets requiring focus management. See [ARIA practices for disclosure navigation](https://www.w3.org/TR/wai-aria-practices-1.2/examples/disclosure/disclosure-navigation.html) for an explanation and additional examples. ### Example 2: menubar submenu option picker The following snippet of code is a popup menu nested in a menubar. It is displayed when the menu button is activated. It is a menu to select the text color from a list of color options: ```html <div> <button type="button" aria-haspopup="menu" aria-controls="colormenu" tabindex="0" aria-label="Text Color: purple"> Purple <span></span> </button> <ul role="menu" id="colormenu" aria-label="Color Options" tabindex="-1"> <li role="menuitemradio" aria-checked="true" style="color: purple" tabindex="-1"> Purple </li> <li role="menuitemradio" aria-checked="false" style="color: magenta" tabindex="-1"> Magenta </li> <li role="menuitemradio" aria-checked="false" style="color: black;" tabindex="-1"> Black </li> </ul> </div> ``` The button that opens the menu has [`aria-haspopup="menu"`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-haspopup) set, explicitly indicating that the popup it controls is a `menu`. For a menu to open, the user generally interacts with a menu button as the opener. The menu button must be focusable and respond to both click and keyboard events. When focused, selecting <kbd>Enter</kbd>, <kbd>Space</kbd>, <kbd>Down Arrow</kbd>, or the <kbd>Up Arrow</kbd> should open the menu and place focus on a menu item. The opening and closing of the menu toggles the [`aria-expanded="true"`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-expanded) attribute on the button. It is added when the menu is open. Removed or set to `false` when the menu is closed. The `true` value indicates that the menu is displayed and that activating the menu button closes the menu. When the menu is open, the button itself generally does not receive focus as users arrow through the menu items. Rather, <kbd>Escape</kbd> and optionally <kbd>Shift + Tab</kbd> closes the menu and returns focus to the menu button. The `menu` role was set on the {{HTMLElement('ul')}}, identifying the `<ul>` element as a menu. The showing and hiding of the menu can be done with CSS. For example, in these code examples we can use the attribute and next-sibling selectors to toggle the visibility of the menu: ```css [role="menu"] { display: none; } [aria-expanded="true"] + [role="menu"] { display: block; } ``` The navigation example has a static button. The submenu example has a button that gets updated when the user selects a new value. In this case, the `aria-label="Text Color: purple"` is set on the `menu` element. It defines the accessible name for the menu as "Text color: purple"; identifying the purpose of the menu (selecting a text color) and the current value (purple). When a new color is selected, the value of the `aria-label` property should be updated as well. ## Specifications {{Specifications}} ## See also - [`menubar`](/en-US/docs/Web/Accessibility/ARIA/Roles/menubar_role) - [`menuitem`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitem_role) - [`menuitemcheckbox`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemcheckbox_role) - [`menuitemradio`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemradio_role) - [`aria-haspopup`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-haspopup) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/landmark_role/index.md
--- title: "ARIA: landmark role" slug: Web/Accessibility/ARIA/Roles/landmark_role page-type: aria-role spec-urls: https://w3c.github.io/aria/#landmark --- A landmark is an important subsection of a page. The `landmark` role is an abstract superclass for the aria role values for sections of content that are important enough that users will likely want to be able to navigate directly to them. > **Note:** The `landmark` role is an [abstract role](/en-US/docs/Web/Accessibility/ARIA/Roles#6._abstract_roles). It is included here for completeness of documentation. It should not be used by web authors. ## Description A `landmark` is an abstract role for a section of content that is important enough that users will likely want to be able to navigate to the section easily and have it included in a dynamically generated summary of the page. Landmarks allow assistive technologies to navigate and to find content quickly. To create a landmark role, define the purpose of the content by using a semantic element such as `<section>`, `<nav>`, or `<main>`, or adding an ARIA role that is a subclass of the `landmark` role such as [`role="banner"`](/en-US/docs/Web/Accessibility/ARIA/Roles/banner_role), [`role="complementary"`](/en-US/docs/Web/Accessibility/ARIA/Roles/complementary_role), or [`role="region"`](/en-US/docs/Web/Accessibility/ARIA/Roles/region_role). Do not use `role="landmark"`. A visible label should be provided, referenced with [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby). If necessary, brief, descriptive, label can be provided with [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label). For screen reader users, adding landmark roles effectively creates 'skip links' for screen reader users, but don't replace in page navigation as the landmark roles are not otherwise surfaced. ## Best Practices Do not use `role="landmark"`. Do use HTML and subclass landmark roles. Landmarks ensure content is in navigable regions. Use {{HTMLElement('main')}} for [`role="main"`](/en-US/docs/Web/Accessibility/ARIA/Roles/main_role), {{HTMLElement('header')}} for [`role="banner"`](/en-US/docs/Web/Accessibility/ARIA/Roles/banner_role), {{HTMLElement('nav')}} for [`role="navigation"`](/en-US/docs/Web/Accessibility/ARIA/Roles/navigation_role), and {{HTMLElement('footer')}} for [`role="contentinfo"`](/en-US/docs/Web/Accessibility/ARIA/Roles/contentinfo_role). It is also good practice to include the role redundantly with the associated semantic element. It is not as good practice to use non-semantic elements, such as {{HTMLElement('div')}}, adding semantics with landmark roles. But do include one or the other or both. Otherwise, your content is no longer as navigable for screen reader users. ## Specifications {{Specifications}} ## See also - [ARIA: `section` role](/en-US/docs/Web/Accessibility/ARIA/Roles/section_role) - [ARIA: `banner` role](/en-US/docs/Web/Accessibility/ARIA/Roles/banner_role) - [ARIA: `complementary` role](/en-US/docs/Web/Accessibility/ARIA/Roles/complementary_role) - [ARIA: `contentinfo` role](/en-US/docs/Web/Accessibility/ARIA/Roles/contentinfo_role) - [ARIA: `form` role](/en-US/docs/Web/Accessibility/ARIA/Roles/form_role) - [ARIA: `main` role](/en-US/docs/Web/Accessibility/ARIA/Roles/main_role) - [ARIA: `navigation` role](/en-US/docs/Web/Accessibility/ARIA/Roles/navigation_role) - [ARIA: `region` role](/en-US/docs/Web/Accessibility/ARIA/Roles/region_role) - [ARIA: `search` role](/en-US/docs/Web/Accessibility/ARIA/Roles/search_role) - [Using HTML landmark roles to improve accessibility](/en-US/blog/aria-accessibility-html-landmark-roles/) on MDN blog (2023) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/menubar_role/index.md
--- title: "ARIA: menubar role" slug: Web/Accessibility/ARIA/Roles/menubar_role page-type: aria-role spec-urls: - https://w3c.github.io/aria/#menubar - https://www.w3.org/WAI/ARIA/apg/patterns/menubar/examples/menubar-navigation/ --- A `menubar` is a presentation of `menu` that usually remains visible and is usually presented horizontally. ## Description A menu is a widget that offers a list of choices to the user, such as a set of actions or functions. The menubar type of menu is usually presented as a persistently visible horizontal bar of commands. Menubars behave like native operating system menubars, such as the menubars containing pull down menus, commonly found at the top of many desktop application windows. The `menubar` role is used to create a menu bar similar to those found near the top of the window in many desktop applications, visually persistent, typically horizontal, bar of menu items offering the user quick access to a consistent set of commands. A `menubar` contains three types of menu items, including [`menuitem`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitem_role), [`menuitemradio`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemradio_role) and [`menuitemcheckbox`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemcheckbox_role). These menu items may optionally be nested in one or more [`group`](/en-US/docs/Web/Accessibility/ARIA/Roles/group_role) containers. Groups or items may optionally by separated with [`separator`](/en-US/docs/Web/Accessibility/ARIA/Roles/separator_role) elements. While every menu item must be able to receive focus, even if disabled, the `group` and `separator` elements are not focusable. An example of a native menubar is the bar which may be present at the top of the screen if you are reading this in a desktop browser. An example of a web-based menubar is the horizontal menu bar that reads "File Edit View Insert Format", etc., which is usually visible under the document name in a Google doc. Menubar interactions should be similar to the typical menu bar interaction in a desktop graphical user interface. In Google Docs, each of those menu items is a `menuitem` with a popup submenu, so each has an `aria-haspopup` attribute set to `true`. The `menubar` element does not. The menubar and all the menu items are focusable and have a [tabindex](/en-US/docs/Web/HTML/Global_attributes/tabindex) attribute set. When the menubar receives focus through tabbing, keyboard focus is placed on the first menuitem. Each item in the menu has `tabindex` set to `-1`, except the first item has which has its `tabindex` set to `0`. If a menubar receives focus as a result of a context action, such as a shortcut key, <kbd>Escape</kbd> or <kbd>Enter</kbd> may return focus to the invoking context. That said, make sure not to create shortcut keys that interfere with user agent, operating system, or assistive technology shortcuts - any UA, OS, or AT. Every menu item, no matter how deeply nested, is able to receive focus, even if disabled. If a `menubar` has a visible label, include [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) set to a value that refers to the labelling element. Otherwise, provide the menubar with an accessible name by including a descriptive [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label). A `menuitem` element in the `menubar` can contain a child submenu of menu items. Submenus can be nested several deep. Generally, the outer `menubar` is horizontal and all the submenus are vertical. If this is not the case, if your menubar is vertical, include [`aria-orientation="vertical"`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-orientation) on the `menubar` element. Otherwise, this attribute is not necessary, as the default value is horizontal. ### Associated WAI-ARIA roles, states, and properties - [`group`](/en-US/docs/Web/Accessibility/ARIA/Roles/group_role) role - : Identifies a set of menu items - [`menuitem`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitem_role) role - : An option in a set of choices contained by a `menubar`. May have a submenu. - [`menuitemradio`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemradio_role) role - : A checkable menu item in a set of elements with the same role, only one of which can be checked at a time. - [`menuitemcheckbox`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemcheckbox_role) role - : a menu item with a checkable state whose possible values are `true`, `false`, or `mixed`. - [`aria-orientation`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-orientation) - : Include `aria-orientation="vertical"` on `menubar` element if it's the menubar is vertical. The default orientation is `horizontal`. ### Keyboard interactions When focus is in a `menubar` it is always on a menu item within the menu bar. When focus is on a top level `menuitem` in a menu bar, the following keyboard interactions must be supported: - <kbd>Down Arrow</kbd> - : If the currently focused `menuitem` has a submenu, opens the submenu and places focus on the first item in the submenu. - <kbd>Up Arrow</kbd> - : (Optional) If the currently focused `menuitem` has a submenu, opens the submenu and places focus on the _last_ item in the submenu. - <kbd>Right Arrow</kbd> - : Moves focus to the next item, optionally wrapping from the last to the first. - <kbd>Left Arrow</kbd> - : Moves focus to the previous item, optionally wrapping from the first to the last. - <kbd>Home</kbd> - : If arrow key wrapping is not supported, moves focus to the first item in the `menubar`. - <kbd>End</kbd> - : If arrow key wrapping is not supported, moves focus to the last item in the `menubar`. - <kbd>Tab</kbd> - : Moves focus to the next element in the tab sequence. If that makes it exit the menubar, all submenus in the menubar get closed. - <kbd>shift + Tab</kbd> - : Moves focus to the previous element in the tab sequence. If that makes it exit the menubar, all submenus in the menubar get closed. See [`menuitem` keyboard interactions](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitem_role#keyboard_interactions), [`menuitemradio` keyboard interactions](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemradio_role#keyboard_interactions), and [`menuitemcheckbox` keyboard interactions](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemcheckbox_role#keyboard_interactions) for more information on keyboard interactions when focus is on a menuitem in a menubar (which it always is). Note: The above interactions assumed the `menubar` is horizontal. If the `menubar` is vertical, include `aria-orientation="vertical"` and change the following keyboard keys accordingly: - <kbd>Down Arrow</kbd> - : Performs like the <kbd>Right Arrow</kbd> as described above. - <kbd>Up Arrow</kbd> - : Performs like the <kbd>Left Arrow</kbd> as described above - <kbd>Right Arrow</kbd> - : Performs like the <kbd>Down Arrow</kbd> as described above. - <kbd>Left Arrow</kbd> - : Performs as the <kbd>Up Arrow</kbd> as described above ## Examples - [W3C WAI-ARIA practices: navigation `menubar` example](https://www.w3.org/TR/2019/WD-wai-aria-practices-1.2-20191218/examples/menubar/menubar-1/menubar-1.html) - [W3C WAI-ARIA practices: editor `menubar` example](https://www.w3.org/TR/2019/WD-wai-aria-practices-1.2-20191218/examples/menubar/menubar-2/menubar-2.html) ## Specifications {{Specifications}} ## See also - [`toolbar` role](/en-US/docs/Web/Accessibility/ARIA/Roles/toolbar_role) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/marquee_role/index.md
--- title: "ARIA: marquee role" slug: Web/Accessibility/ARIA/Roles/marquee_role page-type: aria-role spec-urls: https://w3c.github.io/aria/#marquee --- A `marquee` is a type of [live region](/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions) containing non-essential information which changes frequently. ## Description The `marquee` role defines an area as a type of live region that presents non-essential information that changes frequently. Examples of marquees include stock tickers and ad banners; information that is not necessarily sought out by the user that may be presented in any order. The main difference between a `marquee` and a [`log`](/en-US/docs/Web/Accessibility/ARIA/Roles/log_role) is that log information is presented in a meaningful order such as a by date. Elements with the role marquee have an implicit [aria-live](/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions) value of `off`. The marquee is required to have an accessible name. Use [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) if a visible label is present, otherwise use [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label). ### Associated WAI-ARIA roles, states, and properties - [`aria-live`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-live) - : Defines when assistive technology should inform the user of updates to content. Elements with the role `marquee` have an implicit [aria-live](https://www.w3.org/TR/wai-aria-1.1/#aria-live) value of `off`, meaning screen readers will not announce changes inside the marquee, even when the user is idle. - [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) or [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) - : The `marquee` is required to have an accessible name. Use `aria-labelledby` if a visible label is present, otherwise use `aria-label`. ## Specifications {{Specifications}} ## See also - [ARIA: `alert` role](/en-US/docs/Web/Accessibility/ARIA/Roles/alert_role) - [ARIA: `log` role](/en-US/docs/Web/Accessibility/ARIA/Roles/log_role) - [ARIA: `status` role](/en-US/docs/Web/Accessibility/ARIA/Roles/status_role) - [ARIA: `timer` role](/en-US/docs/Web/Accessibility/ARIA/Roles/timer_role) - [ARIA live regions](/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/form_role/index.md
--- title: "ARIA: form role" slug: Web/Accessibility/ARIA/Roles/form_role page-type: aria-role spec-urls: - https://w3c.github.io/aria/#form - https://www.w3.org/WAI/ARIA/apg/patterns/landmarks/examples/form.html --- The `form` role can be used to identify a group of elements on a page that provide equivalent functionality to an HTML form. The form is not exposed as a landmark region unless it has an [accessible name](/en-US/docs/Glossary/Accessible_name). ```html <div role="form" id="contact-info" aria-label="Contact information"> <!-- form content --> </div> ``` This is a form that collects and saves a user's contact information. > **Warning:** Use an HTML {{htmlelement("form")}} element to contain your form controls, rather than the ARIA `form` role, unless you have a very good reason. > The HTML `<form>` element is sufficient to tell assistive technologies that there is a form. ## Description A `form` [landmark](/en-US/docs/Web/Accessibility/ARIA/Roles#3._landmark_roles) identifies a region of content that contains a collection of items and objects that, as a whole, combine to create a form when no other named landmark is appropriate (e.g. [`main`](/en-US/docs/Web/Accessibility/ARIA/Roles/main_role) or [`search`](/en-US/docs/Web/Accessibility/ARIA/Roles/search_role)). > **Note:** Using the {{HTMLElement('form')}} element will automatically communicate a section of content as a `form` landmark, if it is provided an accessible name. Developers should always prefer using the correct semantic HTML element over using ARIA. Use the HTML {{HTMLElement('form')}} element if possible. The `<form>` element defines a `form` landmark when it has an accessible name (e.g. [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby), [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) or [`title`](/en-US/docs/Web/HTML/Global_attributes#title)). Make sure to have a unique label on each form in a document to help users understand the purpose of the form. This label should be visible to all users, not just assistive technology users. Use the `search` landmark instead of the `form` landmark when the form is used for search functionality. Use the `role="form"` to identify a region of the page; do not use it to identify every form field. Even if you are using the form landmark instead of `<form>`, you are encouraged to use native HTML form controls like {{HTMLElement('button')}}, {{HTMLElement('input')}}, {{HTMLElement('select')}}, and {{HTMLElement('textarea')}}. ### Associated WAI-ARIA Roles, States, and Properties No role specific states or properties. ### Keyboard Interactions No role specific keyboard interactions ### Required JavaScript features - `onsubmit` - : The onSubmit event handler handles the event raised when the form is submitted. Anything that is not a `<form>` cannot be submitted, therefore you would have to use JavaScript to build an alternative data submission mechanism, for example with {{domxref("fetch()")}}. ## Examples ```html <div role="form" id="send-comment" aria-label="Add a comment"> <label for="username">Username</label> <input id="username" name="username" autocomplete="nickname" autocorrect="off" type="text" /> <label for="email">Email</label> <input id="email" name="email" autocomplete="email" autocapitalize="off" autocorrect="off" spellcheck="false" type="text" /> <label for="comment">Comment</label> <textarea id="comment" name="comment"></textarea> <input value="Comment" type="submit" /> </div> ``` It is recommended to use `<form>` instead. ```html <form id="send-comment" aria-label="Add a comment">…</form> ``` ## Accessibility concerns ### Use sparingly [Landmark roles](/en-US/docs/Web/Accessibility/ARIA/Roles#3._landmark_roles) are intended to identify larger overall sections of the document. Using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page. ### Inputs are not forms You do not need to declare `role="form"` on every [form element](/en-US/docs/Web/HTML/Element#forms) (inputs, text areas, selects, etc.). It should be declared on the HTML element that wraps the form elements. Ideally, use the {{HTMLElement('form')}} element as the wrapping element and do not declare `role="form"`. ### Search If a form is used to search, you should use the more specialized [`role="search"`](/en-US/docs/Web/Accessibility/ARIA/Roles/search_role) value. ### Labeling landmarks Each {{HTMLElement('form')}} element and form `role` that needs to be exposed as a landmark must be given an accessible name. This name will allow an assistive technology user to be able to quickly understand the purpose of the form landmark. Use an `aria-labelledby`, `aria-label` or `title` on the same element that was given the `role="form"` to provide it an accessible name. #### Using `role="form"` ```html <div role="form" id="gift-cards" aria-label="Purchase a gift card"> <!-- form content --> </div> ``` #### Redundant descriptions Screen readers will announce the type of role the landmark is. Because of this, you do not need to describe what the landmark is in its label. For example, a declaration of `role="form"` with an of `aria-label="Contact form"` may be announced redundantly as, "contact form form". ## Best practices ### Prefer HTML Using the {{HTMLElement('form')}} element will automatically communicate a section has a role of `form`. If at all possible, prefer using it instead. ## Specifications {{Specifications}} ## See also - The {{HTMLElement('form')}} element - The {{HTMLElement('legend')}} element - [form (role): Accessible Rich Internet Applications (WAI-ARIA) 1.1](https://www.w3.org/TR/wai-aria/#form) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/composite_role/index.md
--- title: "ARIA: composite role" slug: Web/Accessibility/ARIA/Roles/composite_role page-type: aria-role spec-urls: https://w3c.github.io/aria/#composite --- The `composite` [abstract role](/en-US/docs/Web/Accessibility/ARIA/Roles#6._abstract_roles) indicates a widget that may contain navigable descendants or owned children. > **Note:** The `composite` role is an abstract role. It is included here for completeness of documentation. It should not be used by web authors. ## Description `Composite` is an abstract role used for the ontology. Don't use this role in content. Instead, use the composite subclasses of [`grid`](/en-US/docs/Web/Accessibility/ARIA/Roles/grid_role), [`select`](/en-US/docs/Web/Accessibility/ARIA/Roles/select_role), [`spinbutton`](/en-US/docs/Web/Accessibility/ARIA/Roles/spinbutton_role), and [`tablist`](/en-US/docs/Web/Accessibility/ARIA/Roles/tablist_role) ## Best Practices Do not use. ## Specifications {{Specifications}} ## See also - [ARIA: `widget` role](/en-US/docs/Web/Accessibility/ARIA/Roles/widget_role) - [ARIA: `grid` role](/en-US/docs/Web/Accessibility/ARIA/Roles/grid_role) - [ARIA: `select` role](/en-US/docs/Web/Accessibility/ARIA/Roles/select_role) - [ARIA: `spinbutton` role](/en-US/docs/Web/Accessibility/ARIA/Roles/spinbutton_role) - [ARIA: `tablist` role](/en-US/docs/Web/Accessibility/ARIA/Roles/tablist_role) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/heading_role/index.md
--- title: "ARIA: heading role" slug: Web/Accessibility/ARIA/Roles/heading_role page-type: aria-role spec-urls: - https://w3c.github.io/aria/#heading - https://www.w3.org/WAI/ARIA/apg/practices/structural-roles/#when_to_use_structural_roles --- The `heading` role defines this element as a heading to a page or section, with the [`aria-level`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-level) attribute providing for more structure. ## Description The heading role indicates to assistive technologies that this element should be treated like a heading. Screen readers would read the text and indicate that it is formatted like a heading. In addition, the level tells assistive technologies which part of the page structure this heading represents. A level 1 heading, indicated with `aria-level="1"`, usually indicates the main heading of a page, a level 2 heading, defined with `aria-level="2"` the first subsection, a level 3 is a subsection of that, and so on. ```html <div role="heading" aria-level="1">This is a main page heading</div> ``` This defines the text in the `<div>` to be the main heading of the page, indicated by being level 1 via the `aria-level` attribute. Opt for using the {{HTMLElement("Heading_Elements", "h1")}} (through {{HTMLElement("Heading_Elements", "h6")}}) element instead. ```html <h1>This is a main page heading</h1> ``` ### Associated WAI-ARIA roles, states, and properties - [`aria-level`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-level) - : The `aria-level` attribute specifies the heading level in the document structure. If no level is present, a value of 2 is the default. ### Keyboard interactions This role does not require any special keyboard navigation. As with any heading, giving it an ID ensures it can be referenced from anchor links, making it accessible via the keyboard. ### Required JavaScript features - Required event handlers - : None. - Changing attribute values - : Usually not required, unless dynamically inserting content. In that case, the newly-added headings need `aria-level` attributes whose values are consistent with the rest of the document structure. > **Note:** Instead of using a `<div>` or `<span>` with a `heading` role and `aria-level`, consider using a native {{HTMLElement("Heading_Elements", "h1")}} through {{HTMLElement("Heading_Elements", "h6")}} elements instead to indicate that this text is a heading, and what part of the structure it represents. ## Examples The following shows a typical page structure. ```html <div id="container"> <div role="heading" aria-level="1">The main page heading</div> <p>This article is about showing a page structure.</p> <div role="heading" aria-level="2">Introduction</div> <p>An introductory text.</p> <div role="heading" aria-level="2">Chapter 1</div> <p>Text</p> <div role="heading" aria-level="3">Chapter 1.1</div> <p>More text in a sub section.</p> </div> ``` However, instead, you should do: ```html <div id="container"> <h1>The main page heading</h1> <p>This article is about showing a page structure.</p> <h2>Introduction</h2> <p>An introductory text.</p> <h2>Chapter 1</h2> <p>Text</p> <h3>Chapter 1.1</h3> <p>More text in a sub section.</p> </div> ``` ## Accessibility concerns > **Warning:** Using [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) or [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) will hide the content of your heading from assistive technologies, reading the label instead of the heading. If you must use the `heading` role and [`aria-level`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-level) attribute, do not go over level 6 so that you are consistent with HTML. Although theoretically you can go higher, and some screen readers may support it, the results can be unpredictable with other browser and screen reader combinations. ## Best practices The best way to use this role is to **not use it at all**, and instead use the native heading tags {{HTMLElement("Heading_Elements", "h1")}} through {{HTMLElement("Heading_Elements", "h6")}} as shown in the example above. The `heading` role and `aria-level` attribute should only be used to retrofit accessibility on legacy code that you cannot make major changes to. Instead of using the ARIA `heading` role, use the semantic HTML element: | HTML Element | `heading` role | | ----------------------------------------- | ------------------------------------- | | {{HTMLElement("Heading_Elements", "h1")}} | `<div role="heading" aria-level="1">` | | {{HTMLElement("Heading_Elements", "h2")}} | `<div role="heading" aria-level="2">` | | {{HTMLElement("Heading_Elements", "h3")}} | `<div role="heading" aria-level="3">` | | {{HTMLElement("Heading_Elements", "h4")}} | `<div role="heading" aria-level="4">` | | {{HTMLElement("Heading_Elements", "h5")}} | `<div role="heading" aria-level="5">` | | {{HTMLElement("Heading_Elements", "h6")}} | `<div role="heading" aria-level="6">` | ### Added benefits None. ## Specifications {{Specifications}} ## Precedence order The heading role overrides the native semantic meaning of the element it is being used for. The `aria-level` attribute, in addition, determines what level of heading is being exposed. ## See also - [`<h1>` through `<h6>`: The HTML Section Heading elements](/en-US/docs/Web/HTML/Element/Heading_Elements) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/command_role/index.md
--- title: "ARIA: command role" slug: Web/Accessibility/ARIA/Roles/command_role page-type: aria-role spec-urls: https://w3c.github.io/aria/#command --- The `command` role defines a widget that performs an action but does not receive input data. > **Note:** The `command` role is an abstract role. It is included here for completeness of documentation. It should not be used by web authors. ## Description A command is form of widget that performs an action but does not receive input data. It is a superclass for the widget roles [`button`](/en-US/docs/Web/Accessibility/ARIA/Roles/button_role), [`link`](/en-US/docs/Web/Accessibility/ARIA/Roles/link_role), and [`menuitem`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitem_role) ## Best Practices Do not use. ## Specifications {{Specifications}} ## See also - [ARIA: `widget` role](/en-US/docs/Web/Accessibility/ARIA/Roles/widget_role) - [ARIA: `button` role](/en-US/docs/Web/Accessibility/ARIA/Roles/button_role) - [ARIA: `link` role](/en-US/docs/Web/Accessibility/ARIA/Roles/link_role) - [ARIA: `menuitem` role](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitem_role) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/slider_role/index.md
--- title: "ARIA: slider role" slug: Web/Accessibility/ARIA/Roles/slider_role page-type: aria-role spec-urls: https://w3c.github.io/aria/#slider --- The `slider` role defines an input where the user selects a value from within a given range. ## Description The `slider` role is for range input widgets where the user selects a value from within given minimum and maximum values. ### The `slider` role compared other range options ARIA provides developers with six different range [widget roles](/en-US/docs/Web/Accessibility/ARIA/Roles#2._widget_roles), including progressbars, meters, and sliders. The [`progressbar`](/en-US/docs/Web/Accessibility/ARIA/Roles/progressbar_role) role, similar to HTML's {{HTMLElement('progress')}} element, is a read-only range indicating the portion of completion of a task, progressing in a single direction, such as a file upload's loading progress bar that eventually reaches 100% when fully loaded. The [`meter`](/en-US/docs/Web/Accessibility/ARIA/Roles/meter_role) role, similar to HTML's {{HTMLElement('meter')}} element, is a read-only gauge indicating the amount of something within a known range, such as a computer's battery indicator or a car's gas gauge. The `slider` role, similar to HTML's `input` of type `range`, [`<input type="range">`](/en-US/docs/Web/HTML/Element/input/range), is a read-write input range. Sliders allow users to select a value between set minimum and maximum values. The user selects a value by moving a slider thumb along a horizontal or vertical slider to select a value. While all three of these ranges have the same ARIA states and properties, the `slider` role is the only read-write range: it is the only one whose value changes via user interaction. As such, it must be able to receive focus. In addition, keyboard interaction, mouse clicks, and touch interaction must be supported. > **Warning:** To change the slider value, touch-based assistive technologies need to respond to user gestures for increasing and decreasing the value by synthesizing key events. > Fully test slider widgets using assistive technologies on devices where touch is a primary input mechanism before using the `slider` role (and all range widgets). #### Common attributes The [`aria-valuemin`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemin) attribute sets the minimum value. If omitted or not a number, it defaults to `0` (zero). The [`aria-valuemax`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemax) attribute defines the maximum value. If it is missing or not a number, it defaults to 100. The [`aria-valuenow`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuenow) attribute value must be between the minimum and maximum values, inclusive. This attribute is required for `slider` and `meter`, and optional for `progressbar`. For `slider`, unless using the [`<input type="range">`](/en-US/docs/Web/HTML/Element/input/range) element, the `aria-valuenow` value must be updated programmatically when the user updates the value. The optional [`aria-valuetext`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuetext) attribute is included when the `aria-valuenow` numeric value doesn't reflect the intended value of the slider. As the minimum, maximum, and current values are all numeric, when the values those numbers represent are not numeric, the `aria-valuetext` attribute should be included with a string value defining the numeric value. For example, if using a slider for t-shirt sizes, the `aria-valuetext` attribute should shift from xx-small through to XX-large as the `aria-valuenow` increases. The `aria-valuetext` value must be updated as the `value` or `aria-valuenow` is updated. While there is no equivalent HTML attribute for `<input type="range">`, you can include `aria-valuetext` on any {{htmlelement('input')}} type. ARIA attributes are supported on semantic HTML elements. When `aria-valuetext` is an important feature for a slider, consider using {{HTMLElement('select')}} with {{HTMLElement('option')}} elements instead. While not visually a range, every option's value is more accessible to all users, not just users of assistive technology. An accessible name is **required**. If the range's role is applied to an HTML {{HTMLElement('input')}} element (or `<meter>` or `<progress>` element), the accessible name can come from the associated {{HTMLElement('label')}}. Otherwise use [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) if a visible label is present or [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) if a visible label is not present. When not using the HTML {{HTMLElement('input')}} element to create your slider, include the [`tabindex`](/en-US/docs/Web/HTML/Global_attributes#tabindex) attribute to make the slider focusable. Of the three range types, only `slider` is user-interactive, and so is the only one that requires being able to receive focus. Focus should be placed on the slider thumb. Sliders have an implicit [`aria-orientation`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-orientation) value of `horizontal`. This attribute is not supported with `meter` or `progressbar`. ### User interactions Unlike the read-only `meter` and `progressbar` roles, a `slider` is an input, accepting user interaction. In addition to including the [`tabindex`](/en-US/docs/Web/HTML/Global_attributes#tabindex) attribute to enable slider focus, keyboard and pointer device support must be implemented. The slider represents the range of possible values. The position of the slider thumb along the slider represents the current value. User actions that must be supported include changing the value by dragging the thumb or clicking the slider for pointing devices and using directional keys such as arrow keys for the keyboard users. See [keyboard interactions](#keyboard_interactions) below. > **Note:** It is recommended to use native [`<input type="range">`](/en-US/docs/Web/HTML/Element/input/range) elements rather than the `slider` role. User agents provide a stylized widget for the range input element, based on the current `value` as it relates to the minimum and maximum values. When using non-semantic elements, all features of the native semantic element need to be recreated with ARIA attributes, JavaScript and CSS. ### Range with multiple thumbs A multi-thumb slider is a slider with two or more thumbs that each set a value in a group of related values. For example, in a product search, a two-thumb slider could be used to enable users to set the minimum and maximum price limits for the search. In many two-thumb sliders, the thumbs are not allowed to pass one another, such as when the slider sets the minimum and maximum values for a range. For example, in a price-range selector, the maximum value of the thumb that sets the lower end of the range is limited by the current value of the thumb that sets the upper end of the range. The minimum value of the upper-end thumb is also limited by the current value of the lower-end thumb. It is not a requirement that the thumbs in multi-thumb sliders be dependent on the other thumb values, but intuitive user experience is a requirement, so it is recommended to avoid this anti-pattern. ### All descendants are presentational There are some types of user interface components that, when represented in a platform accessibility API, can only contain text. Accessibility APIs do not have a way of representing semantic elements contained in a `slider`. To deal with this limitation, browsers, automatically apply role [`presentation`](/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role) to all descendant elements of any `slider` element as it is a role that does not support semantic children. For example, consider the following `slider` element, which contains a heading. ```html <div role="slider"><h3>Temperature in Celsius</h3></div> ``` Because descendants of `slider` are presentational, the following code is equivalent: ```html <div role="slider"><h3 role="presentation">Temperature in Celsius</h3></div> ``` From the assistive technology user's perspective, the heading does not exist since the previous code snippets are equivalent to the following in the [accessibility tree](/en-US/docs/Glossary/Accessibility_tree): ```html <div role="slider">Temperature in Celsius</div> ``` ## Associated roles, states, and properties - [`aria-valuenow`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuenow) (required) - : Set to a decimal value between `aria-valuemin` and `aria-valuemax`, indicating the current value of the slider. - [`aria-valuetext`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuetext) - : Assistive technologies often present the value of `aria-valuenow` as a number. If this would not be accurate, use `aria-valuetext` to provide the slider with a more understandable value. - [`aria-valuemin`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemin) - : Set to a decimal value representing the minimum value, and less than `aria-valuemax`. If not present, the default value is 0. - [`aria-valuemax`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemax) - : Set to a decimal value representing the maximum value, and greater than `aria-valuemin`. If not present, the default value is 100. - [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) or [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) - : Defines the string value or identifies the element (or elements) that label the slider element providing an accessible name. An accessible name is required. - [`aria-orientation`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-orientation) - : Indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous. With a slider, the implicit value is `horizontal` but can be set to `vertical`. As it has an implicit value, the slider orientation is never ambiguous. ## Examples In the example below, we create a vertical thermometer with which the user can set the room temperature: ```html <div> <div id="temperatureLabel">Temperature</div> <div id="temperatureValue">20°C</div> <div id="temperatureSlider"> <div id="temperatureSliderThumb" role="slider" aria-labelledby="temperatureLabel" aria-orientation="vertical" tabindex="0" aria-valuemin="15.0" aria-valuemax="25.0" aria-valuenow="20.0" aria-valuetext="20 degrees Celsius" style="top: calc((25 - 20)*2rem - 0.5rem)"></div> </div> </div> ``` The position of the thumb is the maximum value minus the current value times the height of one degree, minus half the height of the thumb to center it. The rest of the styles are static. ```css [id="temperatureSlider"] { position: relative; height: 20rem; width: 1rem; outline: 1px solid; margin: 3rem; } [id="temperatureSliderThumb"] { position: absolute; height: 1rem; width: 2rem; background-color: currentcolor; left: -0.5rem; } ``` For this example to work, we have to write a script to handle all keyboard and pointer events, including event listeners for `pointermove`, `pointerup`, `focus`, `blur`, and `keydown`, and provide styles for the default state and when the thumb and slider receive focus. The position of the thumb, the `aria-valuenow` and `aria-valuetext` values, and the inner text of the element with the [`id`](/en-US/docs/Web/HTML/Global_attributes#id) "temperatureValue" need to be updated every time <kbd>ArrowLeft</kbd>, <kbd>ArrowDown</kbd>, <kbd>ArrowRight</kbd>, <kbd>ArrowUp</kbd>, <kbd>Home</kbd>, <kbd>End</kbd>, and, optionally, <kbd>PageDown</kbd> and <kbd>PageUp</kbd> keys are released and when the user drags the thumb or otherwise clicks on the temperature slider. Using semantic HTML, this could have been written as: ```html <label for="temperature"> Temperature </label> <output id="temperatureValue">20°C</output> <input type="range" id="temperatureSlider" min="15" max="25" step="0.1" value="20" aria-valuetext="20 degrees celsius" style="transform: rotate(-90deg);" /> ``` By using {{HTMLElement('input')}}, we get an already-styled range-input widget with keyboard focus, focus styling, keyboard interactions, and `value` updated on user interaction for free. We still need to use JavaScript to change the `aria-valuetext` and the value of the {{HTMLElement('output')}} element. There are a few ways to make a range input vertical. In this example, we used [CSS transforms](/en-US/docs/Web/CSS/transform). ## Keyboard interactions | Key(s) | Action | | -------------------- | ------------------------------------------------------------------- | | Right and Up arrows | Increase the selected value by one step | | Left and Down arrows | Decrease the selected value by one step | | Page Up | (Optional) increase the value by a set amount greater than one step | | Page Down | (Optional) decrease the value by a set amount greater than one step | | Home | Set the slider to the minimum value. | | End | Set the slider to the maximum value. | For the optional <kbd>Page Up</kbd> and <kbd>Page Down</kbd> keys, the change in slider value should be by an amount larger than the step changes made by up and down arrows. ## Best practices If the slider is describing the loading progress of a particular region of a page, include the [`aria-describedby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby) attribute to reference the slider status, and set the [`aria-busy`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-busy) attribute to `true` on the region until it is finished loading. HTML's `<input type="range">` implicitly has the `role` of `slider`. Do not use `aria-valuemax` or `aria-valuemin` attributes on `<input type="range">` elements; use `min` and `max` instead. Otherwise, any global `aria-*` attributes and any other `aria-*` attributes applicable to the slider role. ### Prefer HTML It is recommended to use a native {{HTMLElement("input")}} of type `range`, [`<input type="range">`](/en-US/docs/Web/HTML/Element/input/range), rather than the `slider` role. ## Specifications {{Specifications}} ## See also - [`<input type="range">`](/en-US/docs/Web/HTML/Element/input/range), - HTML {{HTMLElement('progress')}} element - HTML {{HTMLElement('meter')}} element - Other range widgets include: - [`meter`](/en-US/docs/Web/Accessibility/ARIA/Roles/meter_role) - [`scrollbar`](/en-US/docs/Web/Accessibility/ARIA/Roles/scrollbar_role) - [`separator`](/en-US/docs/Web/Accessibility/ARIA/Roles/separator_role) (if focusable) - [`progressbar`](/en-US/docs/Web/Accessibility/ARIA/Roles/progressbar_role) - [`spinbutton`](/en-US/docs/Web/Accessibility/ARIA/Roles/spinbutton_role) - Working examples: - [Horizontal Multi-Thumb Slider](https://www.w3.org/TR/2019/WD-wai-aria-practices-1.2-20191218/examples/slider/multithumb-slider.html) - [Horizontal Slider](https://www.w3.org/TR/2019/WD-wai-aria-practices-1.2-20191218/examples/slider/slider-1.html) - [Slider with `aria-orientation` and `aria-valuetext`](https://www.w3.org/TR/2019/WD-wai-aria-practices-1.2-20191218/examples/slider/slider-2.html) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/gridcell_role/index.md
--- title: "ARIA: gridcell role" slug: Web/Accessibility/ARIA/Roles/gridcell_role page-type: aria-role --- The [gridcell role](https://www.w3.org/TR/wai-aria-1.1/#gridcell) is used to make a cell in a [grid](/en-US/docs/Web/Accessibility/ARIA/Roles/grid_role) or [treegrid](/en-US/docs/Web/Accessibility/ARIA/Roles/treegrid_role). It is intended to mimic the functionality of the HTML {{HTMLElement('td')}} element for table-style grouping of information. ```html <div role="gridcell">Potato</div> <div role="gridcell">Cabbage</div> <div role="gridcell">Onion</div> ``` Elements that have `role="gridcell"` applied to them must be the child of an element with a role of [`row`](/en-US/docs/Web/Accessibility/ARIA/Roles/row_role). ```html <div role="row"> <div role="gridcell">Jane</div> <div role="gridcell">Smith</div> <div role="gridcell">496-619-5098</div> … </div> ``` The first rule of ARIA is if a native HTML element or attribute has the semantics and behavior you require, use it instead of re-purposing an element and adding ARIA. Instead use the HTML {{HTMLElement('td')}} element: ```html <td>Potato</td> <td>Cabbage</td> <td>Onion</td> ``` ## Description ### gridcells with dynamically added, hidden, or removed rows and columns Any element with a `role="gridcell"` applied to it should use ARIA to describe its order in the table-style grouping, provided the table, grid, or treegrid has the ability to have rows and/or columns dynamically added, hidden, or removed. Use [`aria-colindex`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colindex) to describe a `gridcell`'s order in the list of columns, and [`aria-rowindex`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowindex) to describe a gridcell's order in the list of rows. Use [`aria-colcount`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colcount) and [`aria-rowcount`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowcount) on the parent element with [`role="grid"`](/en-US/docs/Web/Accessibility/ARIA/Roles/grid_role) applied to it to set the total number of columns or rows. This sample code demonstrates a table-style grouping of information where the third and fourth columns have been removed. [`aria-colindex`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colindex) is being used to describe the rows' position and allows a person using assistive technology to infer that certain rows have been removed: ```html <div role="grid" aria-colcount="6"> <div role="rowgroup"> <div role="row"> <div role="columnheader" aria-colindex="1">First name</div> <div role="columnheader" aria-colindex="2">Last name</div> <div role="columnheader" aria-colindex="5">City</div> <div role="columnheader" aria-colindex="6">Zip</div> </div> </div> <div role="rowgroup"> <div role="row"> <div role="gridcell" aria-colindex="1">Debra</div> <div role="gridcell" aria-colindex="2">Burks</div> <div role="gridcell" aria-colindex="5">New York</div> <div role="gridcell" aria-colindex="6">14127</div> </div> </div> … </div> ``` ### Describing the position of gridcells when the overall structure is unknown In situations where the table-style grouping of content does not provide information about the columns and rows, gridcells must have their positions programmatically described by using [`aria-describedby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby). The [`id`](/en-US/docs/Web/HTML/Global_attributes/id)s provided for `aria-describedby` should correspond to parent elements intended to be the rows and columns. By referencing the parent elements with roles of [`rowheader`](/en-US/docs/Web/Accessibility/ARIA/Roles/rowheader_role) or [`columnheader`](/en-US/docs/Web/Accessibility/ARIA/Roles/columnheader_role) applied to them via `aria-describedby`, it allows assistive technology to understand the position and relationship of the `gridcell` element to the rest of the table-style grouping of content. ### Interactive grids and treegrids #### Editable cells Both `<td>` elements and elements with a role of `gridcell` applied to them can be made editable, mimicking functionality similar to editing a spreadsheet. This is done by applying the HTML [`contenteditable` attribute](/en-US/docs/Web/HTML/Global_attributes/contenteditable). ```html <td contenteditable="true">Notes</td> <div role="gridcell" contenteditable="true">Item cost</div> ``` `contenteditable` will make the element it is applied to focusable via the <kbd>Tab</kbd> key. If a gridcell is conditionally toggled into a state where editing is prohibited, toggle [`aria-readonly`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-readonly) on the gridcell element. #### Expandable cells In a [treegrid](/en-US/docs/Web/Accessibility/ARIA/Roles/treegrid_role), gridcells may be made expandable by toggling the [`aria-expanded`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-expanded) attribute. Note that if this attribute is provided, it applies only to the individual gridcell. ### Associated WAI-ARIA Roles, States, and Properties - `grid` - : Communicates that a parent element is a table or tree style grouping of information. - `row` - : Required to communicate the `gridcell` is part of a row of a table-style grouping of information. - `columnheader` - : Specifies which element is the associated column header. - [`aria-colindex`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colindex) - : Identifies the position of an element in relation to the rest of the table-style grouping of information's columns. - `rowheader` - : Specifies which element is the associated row header. - [`aria-rowindex`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowindex) - : Identifies the position of an element in relation to the rest of the table-style grouping of information's rows. ### Examples The following example creates a table-style grouping of information: ```html <h3 id="table-title">Jovian gas giant planets</h3> <div role="grid" aria-describedby="table-title"> <div role="rowgroup"> <div role="row"> <div role="columnheader">Name</div> <div role="columnheader">Diameter (km)</div> <div role="columnheader">Length of day (hours)</div> <div role="columnheader">Distance from Sun (10<sup>6</sup>km)</div> <div role="columnheader">Number of moons</div> </div> </div> <div role="rowgroup"> <div role="row"> <div role="gridcell">Jupiter</div> <div role="gridcell">142,984</div> <div role="gridcell">9.9</div> <div role="gridcell">778.6</div> <div role="gridcell">67</div> </div> </div> <div role="rowgroup"> <div role="row"> <div role="gridcell">Saturn</div> <div role="gridcell">120,536</div> <div role="gridcell">10.7</div> <div role="gridcell">1433.5</div> <div role="gridcell">62</div> </div> </div> </div> ``` ## Accessibility concerns Support for `gridcell` and certain `gridcell` related ARIA roles and properties have poor support with assistive technologies. If at all possible, use [HTML table markup](/en-US/docs/Web/HTML/Element/table) in their place. ## Best practices The first rule of ARIA is: if a native HTML element or attribute has the semantics and behavior you require, use it instead of re-purposing an element and adding an ARIA role, state or property to make it accessible. As such, it is recommended to use [native HTML table markup](/en-US/docs/Web/HTML/Element/table) instead of recreating a table's form and functionality with ARIA and JavaScript. ## See also - [The Table element](/en-US/docs/Web/HTML/Element/table) - [ARIA: Grid role](/en-US/docs/Web/Accessibility/ARIA/Roles/grid_role) - [Grid Role - Maxability](https://www.maxability.co.in/wai-aria-overview/grid-role/) - [The Table row element](/en-US/docs/Web/HTML/Element/tr) - [ARIA: row role](/en-US/docs/Web/Accessibility/ARIA/Roles/grid_role) - [Row Role - Maxability](https://www.maxability.co.in/wai-aria-overview/row-role/) - [aria-rowcount - Maxability](https://www.maxability.co.in/2018/09/07/aria-rowcount-property/) - [ARIA: rowgroup role](/en-US/docs/Web/Accessibility/ARIA/Roles/rowgroup_role) - [Rowgroup Role - Maxability](https://www.maxability.co.in/wai-aria-overview/rowgroup-role/) - [The Table header element](/en-US/docs/Web/HTML/Element/th) - [Columnheader - Maxability](https://www.maxability.co.in/wai-aria-overview/columnheader-role/) - [aria-colcount - Maxability](https://www.maxability.co.in/2017/07/26/aria-colcount-property/) - [The Table Data Cell element](/en-US/docs/Web/HTML/Element/td) - [gridcell: Accessible Rich Internet Applications (WAI-ARIA) 1.1](https://www.w3.org/TR/wai-aria-1.1/#gridcell) - [Gridcell Role - Maxability](https://www.maxability.co.in/wai-aria-overview/gridcell-role/) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/scrollbar_role/index.md
--- title: "ARIA: scrollbar role" slug: Web/Accessibility/ARIA/Roles/scrollbar_role page-type: aria-role spec-urls: https://w3c.github.io/aria/#scrollbar --- A `scrollbar` is a graphical object that controls the scrolling of content within a viewing area. ## Description A `scrollbar` is a range that controls what part of a viewport's content is currently visible in the viewport's frame; whether the viewport is a full browser size, an iframe, or any element's [block formatting context](/en-US/docs/Web/CSS/CSS_display/Block_formatting_context). ### What is scroll bar Many applications provide native scroll bars when the content area is larger than the application window. Scrollbars generally appear on the right or bottom of the viewing area. Native scroll bars appear as thin rectangular track areas the length of the viewport it controls with a piece of UI called a thumb or scroller that can be dragged along a track to move the associated content within the viewport. Some scrollbars have arrows at each end of the track that allow scrolling the viewport a short set distance when activated. Take this document as an example: if the viewport is the full browser window and the content is taller than the viewport, in most browsers the scroll bar on the right edge of the window represents the overall length of the page and the scroll thumb represents the portion of the page content that is currently in the viewport. Scroll bars may also appear on viewports that are sub-sections of the full browser window. Continuing with this content as our example, if this content is embedded in an {{HTMLElement('iframe')}} or {{HTMLElement('object')}}, the native vertical scroll bar will be the height of the frame. A scroll bar generally is the length of the viewport, but isn't required to be. If you aren't currently seeing a scroll bar, it may be because your browser only displays the scroll bar when scrolling or only when an element's content is too big to fit in its block formatting context. Depending on the browser and operating system, scroll bars can be made to be visible even when the content fits in the viewport when no scrolling is necessary or even possible. ### ARIA `scrollbar` It is always best to use native scroll bars. You can use the CSS {{CSSXref('overflow')}} property to ensure the appearance of native scroll bars. A [CSS scrollbar specification](https://drafts.csswg.org/css-scrollbars/) is being developed. Some browsers allow [styling scroll bars via prefixed pseudo-elements](/en-US/docs/Web/CSS/::-webkit-scrollbar). Because native scroll bar styling has historically been limited, you may come across a scrollbar implemented in JavaScript that you need to support and make fully accessible. For this, you can use the `scrollbar` role to inform assistive technologies that a UI control is an interactive scrollbar. An element with the `scrollbar` role is a graphical object that controls the scrolling of content within a viewing area; it is the ARIA role which indicates an element is a scroll bar. The HTML element that is most similar is the `range` {{HTMLElement('input')}} type, [`<input type="range">`](/en-US/docs/Web/HTML/Element/input/range). The `scrollbar` element has two required attributes: [`aria-controls`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-controls) and [`aria-valuenow`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuenow). The `aria-controls` attribute references the [`id`](/en-US/docs/Web/HTML/Global_attributes#id) of the scrollable area it controls. The `aria-valuenow` property defines the current value of the scrollbar. While the `aria-valuenow` is always required, the [`aria-valuemin`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemin) and [`aria-valuemax`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemax) properties only need to be set for the scrollbar role when the `scrollbar`'s minimum value is not 0 or the maximum value is not 100. The value of `aria-valuenow` must always be between the minimum and maximum inclusive values, or between `0` and `100` inclusive if the minimum and maximum values default to `0` and `100` respectively. `aria-valuenow` communicates how close the viewport is to the bottom of the document. Think of it like a progress bar, where the start of the document is the minimum value and the end of the document is the maximum value. A `scrollbar` represents the current value and range of possible values via the size of the scrollbar and position of the thumb with respect to the visible range of the orientation (horizontal or vertical) it controls. In other words, the `scrollbar` length (height or width) represents all the content within a viewport. The `aria-valuemin` value represents the beginning of the content and the scrollbar, the `aria-valuemax` value represents the end of the content and the end of the scrollbar. The `aria-valuenow` represents the content that is currently visible in the viewport and the current position, or value, of the movable thumb. The `aria-valuenow` value will generally be exposed as a percentage between `aria-valuemin` and `aria-valuemax` calculated by assistive technologies. > **Note:** Assistive technologies generally render the value of `aria-valuenow` as a percent of a range between the value of `aria-valuemin` and `aria-valuemax`, unless [`aria-valuetext`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuetext) is set. It is recommended to set the values for `aria-valuemin`, `aria-valuemax`, and `aria-valuenow` in a manner that is appropriate for this calculation. Like a native scroll bar, users interact with `scrollbar` elements directly or indirectly using mouse, touchpad, keyboard, and voice input. `scrollbar` role implementations must also accommodate all these interaction methods. When using a mouse, the user must be able to activate the `scrollbar` by clicking the scroll arrows at either end of the scroll bar, if present, clicking an empty portion of the scroll track, as well as clicking and dragging the scroll thumb. Keyboard scrolling must also be supported. When focus is within the viewport controlled by a `scrollbar`, the <kbd>Up Arrow</kbd> and <kbd>Down Arrow</kbd> (or <kbd>Left Arrow</kbd> and <kbd>Right Arrow</kbd> for a horizontal scroll bar) should move the scroll bar thumb proportionally. Additionally, the <kbd>Page Up</kbd>, <kbd>Page Down</kbd>, <kbd>Space</kbd>, and <kbd>Shift + Space</kbd> keys must move the content and the scroll thumb the height (or width) of the viewport for each key press until the bottom or top (or left or right) of the content is in view. JavaScript must be used to translate the `scrollbar` action into scrolling commands, providing the user with feedback by: 1. Visually updating the `scrollbar` element, 2. Scrolling the viewport's content, and 3. Updating the [`aria-valuenow`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuenow) property value. The default orientation of the `scrollbar` role is vertical. Including [`aria-orientation="vertical"`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-orientation), in this case, is optional. The orientation represents the orientation of the scrollbar and the scrolling effect on the viewing area controlled by the scrollbar. If the scrolling is left to right or right to left and not top to bottom, include `aria-orientation="horizontal"` on the element with the `scrollbar` role. > **Note:** An accessible name is **required**. If the `scrollbar` role is applied to an HTML {{HTMLElement('input')}} element (or `<meter>` or `<progress>` element), the accessible name can come from the associated {{HTMLElement('label')}}. Otherwise use [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) if a visible label is present or [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) if a visible label is not present. ### All descendants are presentational There are some types of user interface components that, when represented in a platform accessibility API, can only contain text. Accessibility APIs do not have a way of representing semantic elements contained in a `scrollbar`. To deal with this limitation, browsers, automatically apply role [`presentation`](/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role) to all descendant elements of any `scrollbar` element as it is a role that does not support semantic children. For example, consider the following `scrollbar` element, which contains a heading. ```html <div role="scrollbar"><h3>Title of my scrollbar</h3></div> ``` Because descendants of `scrollbar` are presentational, the following code is equivalent: ```html <div role="scrollbar"><h3 role="presentation">Title of my scrollbar</h3></div> ``` From the assistive technology user's perspective, the heading does not exist since the previous code snippets are equivalent to the following in the [accessibility tree](/en-US/docs/Glossary/Accessibility_tree): ```html <div role="scrollbar">Title of my scrollbar</div> ``` ### Associated WAI-ARIA roles, states, and properties - [`aria-controls`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-controls) (Required) - : Identifies the viewport, via the `id`, whose contents controlled by the scrollbar. - [`aria-valuenow`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuenow) (Required) - : Set to a decimal value between `0`, or `aria-valuemin` if present, and `aria-valuemax` indicating the current value of the scrollbar. - [`aria-valuetext`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuetext) - : Assistive technologies often present the value of `aria-valuenow` as a percentage. If this would not be helpful, use this property to make the scrollbar value more understandable to users. - [`aria-valuemin`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemin) - : Set to a decimal value representing the minimum value, and less than `aria-valuemax`. If not present, the default value is `0`. - [`aria-valuemax`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemax) - : Set to a decimal value representing the maximum value, and greater than `aria-valuemin`. If not present, the default value is `100`. - [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) - : When not using a native form control and therefore not able to associate the scrollbar with a {{HTMLElement('label')}}, if visible text is available that can provide the required accessible name, set to the [`id`](/en-US/docs/Web/HTML/Global_attributes#id) of an element containing text serving as a label. Otherwise, use `aria-label`. - [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) - : If no {{htmlelement('label')}} can be used, and no visible text is present that can be referenced by `aria-labelledby`, provides the string value that labels the `scrollbar` element providing the required accessible name. - [`aria-orientation`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-orientation) - : By default, the orientation is `vertical`. The property can be included and set to `horizontal`, `undefined` (the default for all roles unless otherwise specified), or `vertical`. ### Keyboard interactions - <kbd>Up Arrow</kbd> - : The content in the viewport moves up one line with the thumb moving up the scroll bar slider proportionally, until the top of the content and scrollbar are reached. - <kbd>Down Arrow</kbd> - : The content in the viewport moves down one line with the thumb moving down the scroll bar slider proportionally, until the bottom of the content and scrollbar are reached. - <kbd>Left Arrow</kbd> - : With horizontal scrolling, the content in the viewport moves left the width of one character with the thumb moving left across the scroll bar slider proportionally, until the left edge of the content abuts the left end of the viewport and the thumb is aligned on the left end of the scrollbar. - <kbd>Right Arrow</kbd> - : With horizontal scrolling, the content in the viewport moves right the width of one character with the thumb moving right across the scroll bar slider proportionally, until the right edge of the content abuts the right end of the viewport and the thumb is aligned on the right end of the scrollbar. - <kbd>Page Up</kbd> and <kbd>Shift + Space</kbd> - : The content in the viewport moves up the height of one viewport with the thumb moving up the scroll bar slider proportionally, until the top of the content and scrollbar are reached. - <kbd>Page Down</kbd> and <kbd>Space</kbd> - : The content in the viewport moves down the height of one viewport with the thumb moving down the scroll bar slider proportionally, until the bottom of the content and scrollbar are reached.the bottom or top of the content is in view. ## Examples The following is an example of a word likely being too long for a parent container. ```html <span id="pi-label">Pi</div> <div id="pi"> 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679 </div> <div role="scrollbar" aria-labelledby="pi-label" aria-controls="pi" aria-orientation="horizontal" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"> <div id="thumb"></div> </div> ``` When using the ARIA roles instead of native UI features, CSS must be used to style the scrollbar and thumb and JavaScript must be used to handle all keyboard and pointer events. CSS could have been used to ensure the overflowing value of PI had a native scrollbar: ```html <h3 id="PI">Pi</h3> <p class="pi" tabindex="0" aria-labelledby="PI"> 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679 </p> ``` ```css .pi { overflow: auto; max-width: 100%; } ``` The above CSS means a native scroll bar will appear when the user interacts with the paragraph's viewport if the length of the longest word in the paragraph is wider than the paragraphs containing box. The `tabindex` attribute was added to allow people using a keyboard to navigate to, and scroll around the overflowed content. ## Specifications {{Specifications}} ## See also - [`<input type="range">`](/en-US/docs/Web/HTML/Element/input/range), - HTML {{HTMLElement('progress')}} element - HTML {{HTMLElement('meter')}} element - Other range widgets include: - [`meter`](/en-US/docs/Web/Accessibility/ARIA/Roles/meter_role) - [`slider`](/en-US/docs/Web/Accessibility/ARIA/Roles/slider_role) - [`separator`](/en-US/docs/Web/Accessibility/ARIA/Roles/separator_role) (if focusable) - [`progressbar`](/en-US/docs/Web/Accessibility/ARIA/Roles/progressbar_role) - [`spinbutton`](/en-US/docs/Web/Accessibility/ARIA/Roles/spinbutton_role) - [Document `scroll` event](/en-US/docs/Web/API/Document/scroll_event) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/columnheader_role/index.md
--- title: "ARIA: columnheader role" slug: Web/Accessibility/ARIA/Roles/columnheader_role page-type: aria-role spec-urls: - https://w3c.github.io/aria/#columnheader - https://www.w3.org/WAI/ARIA/apg/patterns/table/examples/table/ --- The `columnheader` value of the ARIA role attribute identifies an element as being a cell in a row contains header information for a column, similar to the native {{HTMLElement('th')}} element with column scope. ## Description An element with `role="columnheader"` nested as a descendant for an element with `role="row"`, is a static tabular structure of a column header cell in a tabular container, either a table or grid, or other chart that needs to show data relationships. To be supported, the columnheader must be nested in an element with the [role of `row`](/en-US/docs/Web/Accessibility/ARIA/Roles/row_role). ### Associated WAI-ARIA roles, states, and properties All columnheaders should be nested within a [row](/en-US/docs/Web/Accessibility/ARIA/Roles/row_role). Every row, in turn, should be nested within a [grid](/en-US/docs/Web/Accessibility/ARIA/Roles/grid_role), [table](/en-US/docs/Web/Accessibility/ARIA/Roles/table_role), or [treegrid](/en-US/docs/Web/Accessibility/ARIA/Roles/row_role), alternatively within a [rowgroup](/en-US/docs/Web/Accessibility/ARIA/Roles/rowgroup_role) nested within one of the above. - [`aria-sort`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-sort) - : Only applied to one column header at a time, if any, the `aria-sort` attribute indicates if a column is sorted in the three values of `ascending` or `descending` order, or `none` for not sorted. ### Keyboard interactions This role does not support any specific keyboard interaction. ### Required JavaScript features JavaScript is only required if the `aria-sort` attribute is used. ## Examples ```html <table> <thead> <tr role="row"> <th role="columnheader" scope="col"> <button>First Name</button> </th> <th role="columnheader" scope="col"> <button>Last Name</button> </th> <th role="columnheader" scope="col" aria-sort="ascending"> <button>Company Name</button> </th> <th role="columnheader" scope="col"> <button>Job Title</button> </th> </tr> </thead> <tbody> … </tbody> </table> ``` ## Best Practices Columnheaders should contain a title or header information for the column. The first rule of ARIA is: if a native HTML element or attribute has the semantics and behavior you require, use it instead of re-purposing an element and adding an ARIA role, state or property to make it accessible. It is recommended to use the native HTML `<th>` element with the `scope` attribute set `<th scope="col">` instead of a `<div>` or other element. If you use semantic HTML's `<th scope="col">` the role attribute is not required, but can be included as a back up to ensure the table retains its semantics should the default semantics be removed with a CSS display property value. The `aria-sort` attribute can be added to a `<th scope="col">` even when the ARIA role attribute is not specified. ### Prefer HTML Columnheader has the same semantics `<th scope="col">`. ## Specifications {{Specifications}} ## See also - [`table` role](/en-US/docs/Web/Accessibility/ARIA/Roles/table_role) - [`grid` role](/en-US/docs/Web/Accessibility/ARIA/Roles/grid_role) - [`treegrid` role](/en-US/docs/Web/Accessibility/ARIA/Roles/row_role) - [`row` role](/en-US/docs/Web/Accessibility/ARIA/Roles/row_role) - [`rowgroup` role](/en-US/docs/Web/Accessibility/ARIA/Roles/rowgroup_role) - [The `<th>` element](/en-US/docs/Web/HTML/Element/th) - [The `<table>` element](/en-US/docs/Web/HTML/Element/table) - [The `<tr>` element](/en-US/docs/Web/HTML/Element/tr) - [The `<td>` element](/en-US/docs/Web/HTML/Element/td) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/dialog_role/index.md
--- title: "ARIA: dialog role" slug: Web/Accessibility/ARIA/Roles/dialog_role page-type: aria-role spec-urls: - https://w3c.github.io/aria/#dialog - https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/examples/dialog/ --- The `dialog` role is used to mark up an HTML based application dialog or window that separates content or UI from the rest of the web application or page. Dialogs are generally placed on top of the rest of the page content using an overlay. Dialogs can be either non-modal (it's still possible to interact with content outside of the dialog) or modal (only the content in the dialog can be interacted with). ```html <div role="dialog" aria-labelledby="dialog1Title" aria-describedby="dialog1Desc"> <h2 id="dialog1Title">Your personal details were successfully updated</h2> <p id="dialog1Desc"> You can change your details at any time in the user account section. </p> <button>Close</button> </div> ``` ## Description A dialog is a descendant window of the primary window of a web application. For HTML pages, the primary application window is the entire web document, i.e., the body element. Marking up a dialog element with the `dialog` role helps assistive technology identify the dialog's content as being grouped and separated from the rest of the page content. However, adding `role="dialog"` alone is not sufficient to make a dialog accessible. Additionally, the following needs to be done: - The dialog must be properly labeled - Keyboard focus must be managed correctly The sections below describe how these two requirements can be met. ### Labeling Even though it is not required for the dialog itself to be able to receive focus, it still needs to be labeled. The label given to the dialog will provide contextual information for the interactive controls inside the dialog. In other words, the dialog's label acts like a grouping label for the controls inside it (similar to how a `<legend>` element provides a grouping label for the controls inside a `<fieldset>` element). If a dialog already has a visible title bar, the text inside that bar can be used to label the dialog itself. The best way to achieve this is by using the [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) attribute to the `role="dialog"` element. Additionally, if the dialog contains additional descriptive text besides the dialog title, this text can be associated with the dialog using the [`aria-describedby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby) attribute. This approach is shown in the code snippet below: ```html <div role="dialog" aria-labelledby="dialog1Title" aria-describedby="dialog1Desc"> <h2 id="dialog1Title">Your personal details were successfully updated</h2> <p id="dialog1Desc"> You can change your details at any time in the user account section. </p> <button>Close</button> </div> ``` > **Note:** Keep in mind that a dialog's title and description text do not have to be focusable in order to be perceived by screen readers operating in a non-virtual mode. The combination of the ARIA dialog role and labeling techniques should make the screen reader announce the dialog's information when focus is moved into it. ### Required JavaScript features #### Focus management A dialog has particular requirements for how keyboard focus should be managed: - Dialogs should always have at least one focusable control. For many dialogs, there will be a button like "Close", "OK" or "Cancel". In addition to the needed control, dialogs can contain any number of focusable elements, even entire forms or other container widgets like tabs. - When the dialog appears on the screen, keyboard focus (whose control depends upon the dialog's purpose) should be moved to the default focusable control inside the dialog. For dialogs that only provide a basic message, it could be an "OK" button. For dialogs containing a form it could be the first field in the form. - After the dialog is dismissed, keyboard focus should be moved back to where it was before it moved into the dialog. Otherwise the focus can be dropped to the beginning of the page. - For most dialogs, the expected behavior is that the dialog's tab order _wraps_, which means that when the user tabs through the focusable elements in the dialog, the first focusable element will be focused after the last one has been reached. In other words, the tab order should be contained within and by the dialog. - If the dialog can be moved or resized, ensure that these actions must be performable by keyboard users as well as mouse users. Similarly, if a dialog provides special features like toolbars or context menus, these must be reachable and operable by keyboard users as well. - Dialogs can be modal or non-modal. When a _modal_ dialog appears on the screen, it's not possible to interact with any page content outside the dialog. In other words, the main application UI or page content is considered to be temporarily disabled as long as the modal dialog is showing. For _non-modal_ dialogs it is still possible to interact with content outside of the dialog while the dialog is showing. Note that for non-modal dialogs there will have to be a global keyboard shortcut that allows focus to be moved between opened dialogs and the main page. ### Associated ARIA roles, states, and properties - [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) - : Use this attribute to label the dialog. Often, the value of the `aria-labelledby` attribute will be the id of the element used to title the dialog. - [`aria-describedby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby) - : Use this attribute to describe the contents of the dialog. ### Possible effects on user agents and assistive technology When the `dialog` role is used, the user agent should do the following: - Expose the element as a dialog in the operating system's accessibility API. When the dialog is correctly labeled and focus is moved to an element (often an interactive element, such as a button) inside the dialog, screen readers should announce the dialog's accessible role, name and optionally description, along with announcing the focused element. > **Note:** Opinions may differ on how assistive technology should handle this technique, and the order of announcements may differ depending on the assistive technology used. The information provided above is one of those opinions and may change as the specification is defined. ## Examples ### A dialog containing a form ```html <div role="dialog" aria-labelledby="dialog1Title" aria-describedby="dialog1Desc"> <h2 id="dialog1Title">Subscription Form</h2> <p id="dialog1Desc">We will not share this information with third parties.</p> <form> <p> <label for="firstName">First Name</label> <input id="firstName" type="text" /> </p> <p> <label for="lastName">Last Name</label> <input id="lastName" type="text" /> </p> <p> <label for="interests">Interests</label> <textarea id="interests"></textarea> </p> <p> <input type="checkbox" id="autoLogin" name="autoLogin" /> <label for="autoLogin">Auto-login?</label> </p> <p> <input type="submit" value="Save Information" /> </p> </form> </div> ``` #### Working Examples - [jQuery-UI Dialog](https://jqueryui.com/dialog/) ### Notes > **Note:** While it is possible to prevent keyboard users from moving focus to elements outside of the dialog, screen reader users may still be able to navigate to that content using their screen reader's virtual cursor. > It is important for developers to ensure that content outside of the modal dialog is inaccessible to all users while the modal dialog is active. ## Specifications {{Specifications}} Coming soon ## See also - [ARIA: alertdialog role](/en-US/docs/Web/Accessibility/ARIA/Roles/alertdialog_role) - {{HTMLElement('dialog', 'The HTML <code>&lt;dialog&gt;</code> element')}} <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/document_role/index.md
--- title: "ARIA: document role" slug: Web/Accessibility/ARIA/Roles/document_role page-type: aria-role spec-urls: https://w3c.github.io/aria/#document --- The `document` role is for focusable content within complex composite [widgets](/en-US/docs/Web/Accessibility/ARIA/Roles/widget_role) or [applications](/en-US/docs/Web/Accessibility/ARIA/Roles/application_role) for which assistive technologies can switch reading context back to a reading mode. ## Description The `document` role is for the top container containing content that assistive technology users may want to browse in a reading mode. Only useful on focusable sections within complex composite [widgets](/en-US/docs/Web/Accessibility/ARIA/Roles/widget_role) or [applications](/en-US/docs/Web/Accessibility/ARIA/Roles/application_role), the `document` role informs assistive technologies to the reading context back to a reading mode: The `document` role tells assistive technologies with reading or browse modes to use the document mode to read the content contained within this element. ```html <div role="dialog"> … <div id="InfoText" role="document" tabindex="0"> <p>Some informational text goes here.</p> </div> … <button>Close</button> </div> ``` This example shows a [dialog](/en-US/docs/Web/Accessibility/ARIA/Roles/dialog_role), a complex composite widget role, with some controls and a section with some informational text that the assistive technology user can go into reading mode when tabbed to. By default, web pages are treated as documents; assistive technologies (AT) enter browse or read mode when entering a new web page. This mode can be altered through various roles, including the widget and application roles. The `document` role brings the AT back into browse or read mode. Generally placed within an application role or other interactive widget role, the `document` role is used to indicate a section of a complex composite widget that an assistive technology user should read using its browse or virtual reading mode, if available. Because ATs with reading mode default to that mode for all elements except for those with a widget or application role set, document role is only useful for focusable elements within a widget or application that should be read as static rich text. Adding `role="document"` and `tabindex="0"` to the element containing the text within a widget enables the screen reader user to press the Tab key to place focus on the document element and read the text with the screen reader's reading cursor. Assistive technologies should switch context back to document mode, possibly intercepting from controls rewired for the parent's dynamic context, re-enabling the standard input events, such as Up or Down arrow keyboard events, to control the reading cursor. In contrast to the [`article`](/en-US/docs/Web/Accessibility/ARIA/Roles/article_role) role, the `document` role does not have any relation to other elements with a document role, it merely has a relationship to the containing composite widget. An article can have associated articles. ### Associated WAI-ARIA roles, states, and properties - [`aria-expanded`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-expanded) - : Include with a value of `true` or `false` if the document element is collapsible, to indicate if the document is currently expanded or collapsed. Other values include the default `undefined` which means the document is not collapsible. - tabindex="0" - : Used to make it focusable so the assistive technology user can tab to it and start reading right away. ### Keyboard interactions The element should be made focusable by setting the `tabindex="0"` attribute / value pair on it. This way, the user can tab to it, reading mode is invoked automatically, and the content can be read right away. ### Required JavaScript features None, except as required by any attributes. For example, if the `document` is collapsible, then the state and the value of `aria-expanded` must be maintained. ## Examples An example is Gmail and the single conversation view. GMail is a web application. When in GMail, most user agent interactions are usurped by the application. However, when the Keyboard focus is set on the starting heading on a single conversation that contains the subject of the conversation, the screen reader user can use the reading mode commands to read through the messages, expand or collapse them, and manipulate them. Once focus returns to the message list either by activating the Back button or pressing an associated keystroke, direct application interaction mode is invoked again, and the user can move to a different conversation in the list with the <kbd>arrow</kbd> keys. ## Best practices Always make sure an item with the document role is focusable, by setting the `tabindex` attribute with a value of 0. That will also include it in the tab order. ### Added benefits The document role is an easy way to indirectly control assistive technology behavior by unambiguously stating that this is content the user should read with standard screen reader commands. ## Specifications {{Specifications}} ## See also - [ARIA: `widget` role](/en-US/docs/Web/Accessibility/ARIA/Roles/widget_role) - [ARIA: `application` role](/en-US/docs/Web/Accessibility/ARIA/Roles/application_role) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/tab_role/index.md
--- title: "ARIA: tab role" slug: Web/Accessibility/ARIA/Roles/tab_role page-type: aria-role spec-urls: - https://w3c.github.io/aria/#tab - https://www.w3.org/WAI/ARIA/apg/patterns/tabs/examples/tabs-manual/ --- The ARIA `tab` role indicates an interactive element inside a `tablist` that, when activated, displays its associated `tabpanel`. ```html <button role="tab" aria-selected="true" aria-controls="tabpanel-id" id="tab-id"> Tab label </button> ``` ## Description An element with the `tab` role controls the visibility of an associated element with the [`tabpanel`](/en-US/docs/Web/Accessibility/ARIA/Roles/tabpanel_role) role. The common user experience pattern is a group of visual tabs above, or to the side of, a content area, and selecting a different tab changes the content and makes the selected tab more prominent than the other tabs. Elements with the role `tab` _must_ either be a child of an element with the `tablist` role, or have their `id` as part of the [`aria-owns`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-owns) property of a `tablist`. This combination identifies to assistive technology that the element is part of a group of related elements. Some assistive technology will provide a count of the number of `tab` role elements inside a `tablist`, and inform users of which `tab` they currently have targeted. Further, an element with the `tab` role _should_ contain the [`aria-controls`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-controls) property identifying a corresponding `tabpanel` (that has a `tabpanel` role) by that element's `id`. When an element with the `tabpanel` role has focus, or a child of it has focus, that indicates that the connected element with the `tab` role is the active tab in a `tablist`. When elements with the `tab` role are selected or active they should have their [`aria-selected`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-selected) attribute set to `true`. Otherwise, their `aria-selected` attribute should be set to `false`. When a single-selectable `tablist` is selected or active, the `hidden` attribute of the other tabpanels should be set to true until the user selects the tab associated with that tabpanel. When a multi-selectable `tablist` is selected or active, its corresponding controlled `tabpanel` should have its [`aria-expanded`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-expanded) attribute set to `true` and its `hidden` attribute set to `false`, otherwise the reverse. ### All descendants are presentational There are some types of user interface components that, when represented in a platform accessibility API, can only contain text. Accessibility APIs do not have a way of representing semantic elements contained in a `tab`. To deal with this limitation, browsers, automatically apply role [`presentation`](/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role) to all descendant elements of any `tab` element as it is a role that does not support semantic children. For example, consider the following `tab` element, which contains a heading. ```html <div role="tab"><h3>Title of my tab</h3></div> ``` Because descendants of `tab` are presentational, the following code is equivalent: ```html <div role="tab"><h3 role="presentation">Title of my tab</h3></div> ``` From the assistive technology user's perspective, the heading does not exist since the previous code snippets are equivalent to the following in the [accessibility tree](/en-US/docs/Glossary/Accessibility_tree): ```html <div role="tab">Title of my tab</div> ``` ### Associated roles and attributes - [`aria-selected`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-selected) - : boolean - [`aria-controls`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-controls) - : `id` of element with `tabpanel` role - [id](/en-US/docs/Web/HTML/Global_attributes#id) - : content ### Keyboard interaction | Key | Action | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | <kbd>Tab</kbd> | When focus is outside of the `tablist` moves focus to the active tab. If focus is on the active tab moves focus to the next element in the keyboard focus order, ideally the active tab's associated `tabpanel`. | | <kbd>→</kbd> | Focuses and optionally activates the next tab in the tab list. If the current tab is the last tab in the tab list it activates the first tab. | | <kbd>←</kbd> | Focuses and optionally activates the previous tab in the tab list. If the current tab is the first tab in the tab list it activates the last tab. | | <kbd>Delete</kbd> | When allowed removes the currently selected tab from the tab list. | ### Required JavaScript features > **Note:** While there are ways to build tab-like functionality without JavaScript, there is no substitute combination using only HTML and CSS that will provide the same set of functionality that's required above for accessible tabs with content. ## Example This example combines the role `tab` with `tablist` and elements with `tabpanel` to create an interactive group of tabbed content. Here we are enclosing our group of content in a `div`, with our `tablist` having an `aria-label` which labels it for assistive technology. Each `tab` is a `button` with the attributes previously mentioned. The first `tab` has both `tabindex="0"` and `aria-selected="true"` applied. These two attributes must always be coordinated as such—so when another tab is selected, it will then have `tabindex="0"` and `aria-selected="true"` applied. All unselected tabs must have `aria-selected="false"` and `tabindex="-1"`. All of the `tabpanel` elements have `tabindex="0"` to make them tabbable, and all but the currently active one have the `hidden` attribute. The `hidden` attribute will be removed when a `tabpanel` becomes visible with JavaScript. There is some basic styling applied that restyles the buttons and changes the [`z-index`](/en-US/docs/Web/CSS/z-index) of `tab` elements to give the illusion of it connecting to the `tabpanel` for active elements, and the illusion that inactive elements are behind the active `tabpanel`. ```html <div class="tabs"> <div role="tablist" aria-label="Sample Tabs"> <button role="tab" aria-selected="true" aria-controls="panel-1" id="tab-1" tabindex="0"> First Tab </button> <button role="tab" aria-selected="false" aria-controls="panel-2" id="tab-2" tabindex="-1"> Second Tab </button> <button role="tab" aria-selected="false" aria-controls="panel-3" id="tab-3" tabindex="-1"> Third Tab </button> </div> <div id="panel-1" role="tabpanel" tabindex="0" aria-labelledby="tab-1"> <p>Content for the first panel</p> </div> <div id="panel-2" role="tabpanel" tabindex="0" aria-labelledby="tab-2" hidden> <p>Content for the second panel</p> </div> <div id="panel-3" role="tabpanel" tabindex="0" aria-labelledby="tab-3" hidden> <p>Content for the third panel</p> </div> </div> ``` ```css hidden .tabs { padding: 1em; } [role="tablist"] { margin-bottom: -1px; } [role="tab"] { position: relative; z-index: 1; background: white; border-radius: 5px 5px 0 0; border: 1px solid grey; border-bottom: 0; padding: 0.2em; } [role="tab"][aria-selected="true"] { z-index: 3; } [role="tabpanel"] { position: relative; padding: 0 0.5em 0.5em 0.7em; border: 1px solid grey; border-radius: 0 0 5px 5px; background: white; z-index: 2; } [role="tabpanel"]:focus { border-color: orange; outline: 1px solid orange; } ``` There are two things we need to do with JavaScript: we need to change focus and tab index of our `tab` elements with the right and left arrows, and we need to change the active `tab` and `tabpanel` when we click on a `tab`. To accomplish the first, we listen for the [`keydown`](/en-US/docs/Web/API/Element/keydown_event) event on the `tablist`. If the event's [`key`](/en-US/docs/Web/API/KeyboardEvent/key) is `ArrowRight` or `ArrowLeft`, we react to the event. We start by setting the `tabindex` of the current `tab` element to -1, making it no longer tabbable. Then, if the right arrow is being pressed, we increase our tab focus counter by one. If the counter is greater than the number of `tab` elements we have, we circle back to the first tab by setting that counter to 0. If the left arrow is being pressed, we decrease our tab focus counter by one, and if it is then less than 0, we set it to the number of `tab` elements minus one (to get to the last element). Finally, we set `focus` to the `tab` element whose index is equal to the tab focus counter, and set its `tabindex` to 0 to make it tabbable. To handle changing the active `tab` and `tabpanel`, we have a function that takes in the event, gets the element that triggered the event, the triggering element's parent element, and its grandparent element. We then find all tabs with `aria-selected="true"` inside the parent element and sets it to `false`, then sets the triggering element's `aria-selected` to `true`. After that, we find all `tabpanel` elements in the grandparent element, make them all `hidden`, and finally select the element whose `id` is equal to the triggering `tab`'s `aria-controls` and removes the `hidden` attribute, making it visible. ```js window.addEventListener("DOMContentLoaded", () => { const tabs = document.querySelectorAll('[role="tab"]'); const tabList = document.querySelector('[role="tablist"]'); // Add a click event handler to each tab tabs.forEach((tab) => { tab.addEventListener("click", changeTabs); }); // Enable arrow navigation between tabs in the tab list let tabFocus = 0; tabList.addEventListener("keydown", (e) => { // Move right if (e.key === "ArrowRight" || e.key === "ArrowLeft") { tabs[tabFocus].setAttribute("tabindex", -1); if (e.key === "ArrowRight") { tabFocus++; // If we're at the end, go to the start if (tabFocus >= tabs.length) { tabFocus = 0; } // Move left } else if (e.key === "ArrowLeft") { tabFocus--; // If we're at the start, move to the end if (tabFocus < 0) { tabFocus = tabs.length - 1; } } tabs[tabFocus].setAttribute("tabindex", 0); tabs[tabFocus].focus(); } }); }); function changeTabs(e) { const target = e.target; const parent = target.parentNode; const grandparent = parent.parentNode; // Remove all current selected tabs parent .querySelectorAll('[aria-selected="true"]') .forEach((t) => t.setAttribute("aria-selected", false)); // Set this tab as selected target.setAttribute("aria-selected", true); // Hide all tab panels grandparent .querySelectorAll('[role="tabpanel"]') .forEach((p) => p.setAttribute("hidden", true)); // Show the selected panel grandparent.parentNode .querySelector(`#${target.getAttribute("aria-controls")}`) .removeAttribute("hidden"); } ``` {{EmbedLiveSample("Example", 600, 130)}} ## Best practices It is recommended to use a {{HTMLElement('button')}} element with the role `tab` for their built-in functional and accessible features instead, as opposed to needing to add them yourself. For controlling tab key functionality for elements with the role `tab`, it is recommended to set all non-active elements to `tabindex="-1"`, and to set the active element to `tabindex="0"`. ## Precedence order What are the related properties, and in what order will this attribute or property be read, which property will take precedence over this one, and which property will be overwritten. ## Specifications {{Specifications}} ## See also - HTML {{HTMLElement('button')}} element - [KeyboardEvent.key](/en-US/docs/Web/API/KeyboardEvent/key) - [ARIA `tabpanel` role](/en-US/docs/Web/Accessibility/ARIA/Roles/tabpanel_role) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/region_role/index.md
--- title: "ARIA: region role" slug: Web/Accessibility/ARIA/Roles/region_role page-type: aria-role spec-urls: - https://w3c.github.io/aria/#region - https://www.w3.org/WAI/ARIA/apg/patterns/landmarks/examples/region.html --- The **`region`** role is used to identify document areas the author deems significant. It is a generic landmark available to aid in navigation when none of the other landmark roles are appropriate. ```html <div role="region" aria-label="Example"> <!-- region content --> </div> ``` ## Description The `region` role is an [ARIA landmark](/en-US/docs/Web/Accessibility/ARIA/Roles#3._landmark_roles) role. The `region` role should be reserved for sections of content sufficiently important that users will likely want to navigate to the section easily and to have it listed in a summary of the page. A region role is a more generic term, and should only be used if the section needing to be identified is not accurately described by one of the other landmark roles, such as [`banner`](/en-US/docs/Web/Accessibility/ARIA/Roles/banner_role), [`main`](/en-US/docs/Web/Accessibility/ARIA/Roles/main_role), [`contentinfo`](/en-US/docs/Web/Accessibility/ARIA/Roles/contentinfo_role), [`complementary`](/en-US/docs/Web/Accessibility/ARIA/Roles/complementary_role), or [`navigation`](/en-US/docs/Web/Accessibility/ARIA/Roles/navigation_role). Every element with a `region` role should include a label that describes the purpose of the content in the region, preferably with an [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) referencing a visible header. If no visible appropriate header is present, [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) should be used. The `region` landmark role's content should make sense if separated from the main content of the document. Using the {{HTMLElement('section')}} element will automatically communicate a section has a role of `region` if it is given an accessible name. Developers should always prefer using the correct semantic HTML element, in this case `<section>`, over using ARIA. ### Associated WAI-ARIA Roles, States, and Properties - [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) or [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) - : Use this attribute to label the region. Often, the value of the `aria-labelledby` attribute will be the id of the element used to title the section. If no visible appropriate header is present, `aria-label` should be used. ## Examples ```html <div role="region" aria-labelledby="region-heading"> <h2 id="region-heading"> This heading's `id` attribute helps this region have an accessible name </h2> <!-- region content --> </div> ``` ## Accessibility concerns Use sparingly! [Landmark roles](/en-US/docs/Web/Accessibility/ARIA/Roles#3._landmark_roles) are intended to be used sparingly, to identify larger overall sections of the document. Using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page. Only use the `region` role if no other relevant [content sectioning](/en-US/docs/Web/HTML/Element#content_sectioning) element or [landmark role](/en-US/docs/Web/Accessibility/ARIA/Roles#3._landmark_roles) applies. If multiple regions exist on a page, it may be worth reinvestigating the page's overall structure. ## Best practices ### Prefer HTML Using the {{HTMLElement('section')}} element will automatically communicate that a section has a role of `region` if it is given an accessible name. If at all possible, prefer using {{HTMLElement('section')}} instead. ### Labeling landmarks If there is more than one `region` landmark role in a document, provide a unique label for each one. This label will allow an assistive technology user to be able to quickly understand the purpose of each landmark. ```html <div role="region" aria-labelledby="use-discretion"> <h3 id="use-discretion">Please use the `region` role with discretion</h3> <!-- content --> </div> … <div role="region" aria-labelledby="please-reconsider"> <h3 id="please-reconsider">Please reconsider your document structure</h3> <!-- content --> </div> ``` In this example, the region's label is being generated by the [`aria-labelledby` attribute](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby). ### Scrolling content areas with overflow text If there is a content area with `tabindex="0"`, add `role="region"` to convey to screen reader users that is a generic region. This is done to allow keyboard-only users to scroll regions with overflow text. ### SVG `role="region"` can be declared on areas of {{SVGElement('svg')}} along with an `aria-label` to allow individual sections of the SVG to be described. ## Specifications {{Specifications}} ## See also - The {{HTMLElement('section')}} element - [region (role): Accessible Rich Internet Applications (WAI-ARIA) 1.1](https://www.w3.org/TR/wai-aria/#region) - [ARIA: `banner` role](/en-US/docs/Web/Accessibility/ARIA/Roles/banner_role) - [ARIA: `main` role](/en-US/docs/Web/Accessibility/ARIA/Roles/main_role) - [ARIA: `contentinfo` role](/en-US/docs/Web/Accessibility/ARIA/Roles/contentinfo_role) - [ARIA: `complementary` role](/en-US/docs/Web/Accessibility/ARIA/Roles/complementary_role) - [ARIA: `navigation` role](/en-US/docs/Web/Accessibility/ARIA/Roles/navigation_role) - [Landmark roles: Using ARIA: Roles, States, and Properties](/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques#landmark_roles) - [Using WAI-ARIA Landmarks – 2013 | The Paciello Group](https://www.tpgi.com/using-wai-aria-landmarks-2013/) - [Accessible Landmarks | scottohara.me](https://www.scottohara.me/blog/2018/03/03/landmarks.html) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/directory_role/index.md
--- title: "ARIA: directory role" slug: Web/Accessibility/ARIA/Roles/directory_role page-type: aria-role status: - deprecated spec-urls: https://w3c.github.io/aria/#directory --- The `directory` role was for a list of references to members of a group, such as a static table of contents. > **Warning:** The `directory` role was deprecated in ARIA 1.2 ## Description A directory is a static table of contents, whether linked or unlinked. This includes tables of contents built with lists, including nested lists. Dynamic tables of contents, however, might use a tree role instead. The deprecated `directory` role was used for lists of references to members of a group, such as a static table of contents. Use the [`list`](/en-US/docs/Web/Accessibility/ARIA/Roles/list_role) role instead. Or, better yet, use the {{HTMLElement('ul')}} or {{HTMLElement('ol')}} elements, as using `directory` does not provide any additional benefits to assistive technology users. ## Specifications {{Specifications}} ## See also - [The `list` role](/en-US/docs/Web/Accessibility/ARIA/Roles/list_role) - The {{HTMLElement('ul')}} element - The {{HTMLElement('ol')}} element <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/rowgroup_role/index.md
--- title: "ARIA: rowgroup role" slug: Web/Accessibility/ARIA/Roles/rowgroup_role page-type: aria-role spec-urls: https://w3c.github.io/aria/#rowgroup --- An element with `role="rowgroup"` is a group of [rows](/en-US/docs/Web/Accessibility/ARIA/Roles/row_role) within a tabular structure. A `rowgroup` contains one or more rows of [cells](/en-US/docs/Web/Accessibility/ARIA/Roles/cell_role), [grid cells](/en-US/docs/Web/Accessibility/ARIA/Roles/gridcell_role), [column headers](/en-US/docs/Web/Accessibility/ARIA/Roles/columnheader_role), or [row headers](/en-US/docs/Web/Accessibility/ARIA/Roles/rowheader_role) within a [`grid`](/en-US/docs/Web/Accessibility/ARIA/Roles/grid_role), [`table`](/en-US/docs/Web/Accessibility/ARIA/Roles/table_role) or [`treegrid`](/en-US/docs/Web/Accessibility/ARIA/Roles/treegrid_role). ```html <div role="table" aria-label="Populations" aria-describedby="country_population_desc"> <div id="country_population_desc">World Populations by Country</div> <div role="rowgroup"> <div role="row"> <span role="columnheader" aria-sort="descending">Country</span> <span role="columnheader" aria-sort="none">Population</span> </div> </div> <div role="rowgroup"> <div role="row"> <span role="cell">Finland</span> <span role="cell">5.5 million</span> </div> <div role="row"> <span role="cell">France</span> <span role="cell">67 million</span> </div> </div> </div> ``` ## Description `Rowgroup` establishes a relationship between owned row elements and is a structural equivalent to the {{HTMLElement('thead')}}, {{HTMLElement('tfoot')}} and {{HTMLElement('tbody')}} elements in HTML. There is, however, no differentiation between different types of rowgroups. Their elements must be contained in, or owned by, elements with either the [table](/en-US/docs/Web/Accessibility/ARIA/Roles/table_role) or [grid](/en-US/docs/Web/Accessibility/ARIA/Roles/grid_role) role. Using the native {{HTMLElement('thead')}}, {{HTMLElement('tfoot')}} and {{HTMLElement('tbody')}} HTML elements, whenever possible, is strongly encouraged. To create an ARIA table header, table footer or table body, add `role="rowgroup"` to the element. That rowgroup should be nested within a grid, table or treegrid, encompassing a group of one or more rows. Each row, in turn, contains child cells. These cells can be of different types, depending on whether they are column or row headers, or plain or grid cells. > **Note:** Using the native HTML table element ({{HTMLElement('table')}}) along with the table header ({{HTMLElement('thead')}}), footer ({{HTMLElement('tfoot')}}), and body ({{HTMLElement('tbody')}}) elements whenever possible is strongly encouraged. ### Associated WAI-ARIA roles, states, and properties #### Context roles - [role="table"](/en-US/docs/Web/Accessibility/ARIA/Roles/table_role) - : One of the three possible contexts (along with grid and treegrid) in which you'll find a row. It identifies the row as being part of a non-interactive table structure containing data arranged in rows and columns, similar to the native {{HTMLElement('table')}} HTML element. - [role="grid"](/en-US/docs/Web/Accessibility/ARIA/Roles/grid_role) - : One of the three possible contexts (along with table and treegrid) in which you'll find a row. It identifies the row as being part of a non-interactive table structure containing data arranged in rows and columns, similar to the native {{HTMLElement('table')}} HTML element. - [role="treegrid"](/en-US/docs/Web/Accessibility/ARIA/Roles/treegrid_role) - : Similar to a grid, but with rows that can be expanded and collapsed in the same manner as for a tree. #### Descendant roles - [role="row"](/en-US/docs/Web/Accessibility/ARIA/Roles/row_role) - : A row of cells within a tabular structure. A row contains one or more [cells](/en-US/docs/Web/Accessibility/ARIA/Roles/cell_role), [gridcell](/en-US/docs/Web/Accessibility/ARIA/Roles/gridcell_role), or [column headers](/en-US/docs/Web/Accessibility/ARIA/Roles/columnheader_role), and sometimes a [row header](/en-US/docs/Web/Accessibility/ARIA/Roles/rowheader_role). ### Keyboard interactions None ### Required JavaScript features None. > **Note:** The first rule of ARIA use is if you can use a native feature with the semantics and behavior you require already built in, instead of re-purposing an element and **adding** an ARIA role, state or property to make it accessible, then do so. Employ the HTML `<table>` element instead of the ARIA role of table whenever possible. ## Examples ```html <div role="table" aria-label="Semantic Elements" aria-describedby="semantic_elements_table_desc" aria-rowcount="81"> <div id="semantic_elements_table_desc"> Semantic Elements to use instead of ARIA's roles </div> <div role="rowgroup"> <div role="row"> <span role="columnheader" aria-sort="none">ARIA Role</span> <span role="columnheader" aria-sort="none">Semantic Element</span> </div> </div> <div role="rowgroup"> <div role="row" aria-rowindex="11"> <span role="cell">header</span> <span role="cell">h1</span> </div> <div role="row" aria-rowindex="16"> <span role="cell">header</span> <span role="cell">h6</span> </div> <div role="row" aria-rowindex="18"> <span role="cell">rowgroup</span> <span role="cell">thead</span> </div> <div role="row" aria-rowindex="24"> <span role="cell">term</span> <span role="cell">dt</span> </div> </div> </div> ``` The above is a non-semantic ARIA table with a table header and table body, with five of 81 rows present in the DOM: one within a table header and four rows within the table body. The header row, alone in a header rowgroup, has two column headers. The columns are sortable, but not currently sorted, as indicated by the [`aria-sort`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-sort) property. The table body is a separate rowgroup, with four rows currently in the DOM. Because not all the rows are in the DOM, we've included the [`aria-rowindex`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowindex) property on every row. ## Best practices Only use {{HTMLElement('table')}}, {{HTMLElement('tbody')}}, {{HTMLElement('thead')}}, {{HTMLElement('tr')}}, {{HTMLElement('th')}}, {{HTMLElement('td')}}, and so on for data table structure. You can add these ARIA roles to ensure accessibility should the native semantics of the table be removed, such as with CSS. A relevant use case for the ARIA table role is when the CSS's display property overrides the native semantics of a table, such as by `display: grid`. In this case, you can use the ARIA table roles to add in the semantics. ```html <table role="table" aria-label="Semantic Elements" aria-describedby="semantic_elements_table_desc" aria-rowcount="81"> <caption id="semantic_elements_table_desc"> Semantic Elements to use instead of ARIA's roles </caption> <thead role="rowgroup"> <tr role="row"> <th role="columnheader" aria-sort="none">ARIA Role</th> <th role="columnheader" aria-sort="none">Semantic Element</th> </tr> </thead> <tbody role="rowgroup"> <tr role="row" aria-rowindex="11"> <td role="cell">header</td> <td role="cell">h1</td> </tr> <tr role="row" aria-rowindex="16"> <td role="cell">header</td> <td role="cell">h6</td> </tr> </tbody> </table> ``` Above is the semantic way of writing a table. The ARIA roles are only necessary if the native semantics of the table, and therefore the table rows, are obliterated, such as by setting the [display property to flex or grid](/en-US/docs/Web/CSS/display#accessibility_concerns). ### Added benefits none ## Specifications {{Specifications}} ## See also - [HTML table](/en-US/docs/Web/HTML/Element/table) - [HTML table body](/en-US/docs/Web/HTML/Element/tbody) - [HTML table footer](/en-US/docs/Web/HTML/Element/tfoot) - [HTML table header](/en-US/docs/Web/HTML/Element/thead) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/banner_role/index.md
--- title: "ARIA: banner role" slug: Web/Accessibility/ARIA/Roles/banner_role page-type: aria-role spec-urls: - https://w3c.github.io/aria/#banner - https://www.w3.org/WAI/ARIA/apg/patterns/landmarks/examples/banner.html --- The `banner` role is for defining a global site header, which usually includes a logo, company name, search feature, and possibly the global navigation or a slogan. It is generally located at the top of the page. By default, the HTML's {{htmlelement("header")}} element has an identical meaning to the `banner` landmark, unless it is a descendant of {{htmlelement("aside")}}, {{htmlelement("article")}}, {{htmlelement("main")}}, {{htmlelement("nav")}}, or {{htmlelement("section")}}, at which point {{htmlelement("header")}} exposes a [`generic`](/en-US/docs/Web/Accessibility/ARIA/Roles/generic_role) role, and not the equivalent of the site-wide banner. ## Description A `banner` landmark role overwrites the implicit ARIA role of the container element upon which it is applied. It should be reserved for globally repeating site-wide content that is generally located at the top of every page. The banner typically includes things such as a logo or corporate identity, or possibly a site-specific search tool, and is generally what your marketing team would call the "header" or "top banner" of the site. If the [`header` element](/en-US/docs/Web/HTML/Element/header) technique is not being used for that banner, a declaration of `role="banner"` should be used to define a banner landmark to assistive technologies. Assistive technologies can identify the `header` element of a page as the `banner` if it is a descendant of the [`body` element](/en-US/docs/Web/HTML/Element/body), and not nested within an `article`, `aside`, `main`, `nav` or `section` subsection. Each page may have a `banner` landmark, but each page should generally be limited to a single element with the role of banner. In the case of a page containing nested `document` and/or `application` roles, each nested `document` or `application` role may also have one `banner` landmark. If a page includes more than one `banner` landmark, each should have a unique accessible name. ### Associated ARIA roles, states, and properties None ### Keyboard interactions None ### Required JavaScript features None ## Examples Here's a fake simple banner with a skip to navigation link, a logo, a title and a subtitle. As this is the main header for the site, we've added the `banner` landmark role to the container element. ```html <div role="banner"> <a href="#main" id="skipToMain" class="skiptocontent">Skip To main content</a> <img src="images/w3c.png" alt="W3C Logo" /> <h1>ARIA Landmarks</h1> <p>Identifying page subsections for easy navigation</p> <nav>…</nav> </div> ``` We could also have written the above with the HTML `header` element: ```html <header> <a href="#main" id="skipToMain" class="skiptocontent">Skip To main content</a> <img src="images/w3c.png" alt="W3C Logo" /> <h1>ARIA Landmarks</h1> <p>Identifying page subsections for easy navigation</p> <nav>…</nav> </header> ``` ## Best practices While it is best to use the `header` element and ensure it is not a descendant of any subsection of the page, sometimes you don't have access to the underlying HTML. If this is the case, you can add the role of `banner` to the element of the page which should be exposed as a `banner` with JavaScript. Identifying the page's banner in this way will help improve the site's accessibility. ## Specifications {{Specifications}} ## See also - [HTML `header` element](/en-US/docs/Web/HTML/Element/header) - [WC3 Landmarks Example](https://www.w3.org/WAI/ARIA/apg/patterns/landmarks/examples/banner.html) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/spinbutton_role/index.md
--- title: "ARIA: spinbutton role" slug: Web/Accessibility/ARIA/Roles/spinbutton_role page-type: aria-role spec-urls: https://w3c.github.io/aria/#spinbutton --- The `spinbutton` role defines a type of range that expects the user to select a value from among discrete choices. ## Description The `spinbutton` role indicates that the element is an input widget that restricts its value to a set or range of discrete values. The role also comes with increment and decrement functionality. For example, in a widget that enables users to choose an amount to bet in a game of Texas Holdem, the `spinbutton` role can allow users to select a number between the minimum and maximum bets in increments, as allowed by the current game rules. The spinbutton represents the range of possible values. The value of the spinbutton input represents the current value. Spinbuttons often have three components, including a text field that displays the current value, an increment button, and a decrement button. The text field is usually the only focusable component because the increment and decrement functions are keyboard accessible via arrow keys. Typically, the text field also allows users to directly edit the value. In addition to including the [`tabindex`](/en-US/docs/Web/HTML/Global_attributes#tabindex) attribute to enable spinbutton focus, keyboard and pointer device support must be implemented. Directional keys such as the arrow keys must be supported for keyboard users. Changing the value when increment and decrement buttons are clicked must be supported for pointing devices. See [keyboard interactions](#keyboard_interactions) below. > **Note:** It is recommended to use [`<input type="number">`](/en-US/docs/Web/HTML/Element/input/number) element, or other input types for dates and time that also implicitly have the `role="spinbutton"` semantic, rather than the `spinbutton` role. User agents provide stylized widget for the these input elements which provide default increment, decrement, and native range limiting functionality. When using non-semantic elements, all features of the native semantic element need to be recreated with ARIA attributes, JavaScript, and CSS. ### ARIA range widget options ARIA provides developers with six different range [widget roles](/en-US/docs/Web/Accessibility/ARIA/Roles#2._widget_roles), including progressbars, meters, sliders and spinbuttons. The [`progressbar`](/en-US/docs/Web/Accessibility/ARIA/Roles/progressbar_role) role, similar to HTML's {{HTMLElement('progress')}} element, is a read-only range. It indicates the portion of completion of a task, progressing in a single direction, such as a file upload's loading progress bar that eventually reaches 100% when fully loaded. The [`meter`](/en-US/docs/Web/Accessibility/ARIA/Roles/meter_role) role, similar to HTML's {{HTMLElement('meter')}} element, is a read-only gauge. It indicates the amount of something within a known range, such as a computer's battery indicator or a car's gas gauge. The `slider` role, similar to HTML's `input` of type `range`, [`<input type="range">`](/en-US/docs/Web/HTML/Element/input/range), is a read-write input range. Sliders allow users to select a value between the predefined minimum and maximum values. The user selects a value by moving a slider thumb along a horizontal or vertical slider to select a value. While all three of these ranges have the same ARIA states and properties, the `spinbutton` role is the only read-write range: it is the only one whose value changes via user interaction. As such, it must be able to receive focus. In addition, keyboard interaction, mouse clicks, and touch interaction must be supported. > **Warning:** To change the spinbutton value, touch-based assistive technologies need to respond to user gestures for increasing and decreasing the value by synthesizing key events. > Fully test spinbutton widgets using assistive technologies on devices where touch is a primary input mechanism before using the `spinbutton` role (and all range widgets). #### Common attributes The [`aria-valuemin`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemin) attribute sets the minimum value. If omitted or not a number, it defaults to `0` (zero). The [`aria-valuemax`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemax) attribute defines the maximum value. If it is missing or not a number, it defaults to `100`. The [`aria-valuenow`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuenow) attribute value must be between the minimum and maximum values, both inclusive. This attribute is required for `spinbutton` and `meter`, and optional for `progressbar`. For `spinbutton`, unless using semantic HTML elements like [`<input type="number">`](/en-US/docs/Web/HTML/Element/input/number), if the value is updated, the `aria-valuenow` value must also be updated programmatically. The optional [`aria-valuetext`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuetext) attribute is included when the `aria-valuenow` numeric value doesn't reflect the intended value of the spinbutton. The optional minimum, maximum, and current values should be numeric. When the values these numbers represent are not numeric, the `aria-valuetext` attribute should be included with a string value defining the numeric value. For example, if using a spinbutton for t-shirt sizes, the `aria-valuetext` attribute should shift from `XX-Small` through `XX-Large` as the `aria-valuenow` increases. The `aria-valuetext` value must be updated as the value or `aria-valuenow` is updated. ARIA attributes are supported on semantic HTML elements. While there is no equivalent HTML attribute for `<input>`, you can include `aria-valuetext` on any {{htmlelement('input')}} type. When `aria-valuetext` is an important feature for a spinbutton, consider using {{HTMLElement('select')}} with {{HTMLElement('option')}} elements instead. An accessible name is **required**. If the `spinbutton` role is applied to an HTML {{HTMLElement('input')}} element, the accessible name can come from the associated {{HTMLElement('label')}}. Otherwise, use [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) if a visible label is present or [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) if a visible label is not present. When not using the HTML {{HTMLElement('input')}} element to create your spinbutton, include the [`tabindex`](/en-US/docs/Web/HTML/Global_attributes#tabindex) attribute to make the spinbutton focusable. The `spinbutton` role is user-interactive, and therefore, requires being able to receive focus. Focus should be placed on the spinbutton input and not on the associated buttons that increment and decrement the spinbutton value. ### Descendants limited to buttons or text There are some types of user interface components that, when represented in a platform accessibility API, can only contain specific content. The children or owned elements of `spinbutton` are limited to a textbox and two buttons. Alternatively, the `spinbutton` role can be applied to a `text` input and sibling buttons can be used to support the increment and decrement functions. ## Associated roles, states, and properties - [`aria-valuenow`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuenow) (required) - : Set to a decimal value between `aria-valuemin` and `aria-valuemax`, indicating the current value of the spinbutton. If not present, there is no default value. - [`aria-valuetext`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuetext) - : Assistive technologies often present the value of `aria-valuenow` as a number. If `aria-valuenow` cannot be accurate, use `aria-valuetext` to provide the spinbutton with a more understandable value. - [`aria-valuemin`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemin) - : Set to a decimal value representing the minimum value and less than `aria-valuemax`. If not present, there is no default value. - [`aria-valuemax`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemax) - : Set to a decimal value representing the maximum value and greater than `aria-valuemin`. If not present, there is no default value. - [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) - : Defines the string value or identifies the element (or elements) that label the spinbutton element providing an accessible name. An accessible name is required. - [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) - : Defines a string value that labels the spinbutton element. This provides an accessible name to the element when no visible label is available to provide the required accessible name via {{HTMLElement('label')}} or `aria-labelledby`. ## Examples In the example below, a `spinbutton` role has been defined to allow users to select a day of the month. ```html <p id="day">Enter the day of the month</p> <button type="button" tabindex="-1" aria-label="previous day">˱</button> <div role="spinbutton" tabindex="0" aria-valuenow="1" aria-valuetext="first" aria-valuemin="1" aria-valuemax="31" aria-labelledby="day"> 1 </div> <button type="button" tabindex="-1" aria-label="next day">˲</button> ``` In this example, we included a negative `tabindex` to remove the buttons from the default tabbing order. We also added `tabindex` to a normally non-interactive {{HTMLElement('div')}} to add the `spinbutton` itself to the tabbing order. This example requires JavaScript to handle keyboard actions when the spinbutton has focus and when a mouse user clicks on the buttons. ### With semantic HTML This could have also been written using semantic HTML, removing the need for any CSS or JavaScript and also removing the need to include and provide functionality for extraneous incrementing and decrementing buttons. The code snippet below shows the previous example without the `spinbutton` role and using semantic HTML. ```html <label for="day">Enter the day of the month</label> <input type="number" value="1" aria-valuetext="first" min="1" max="31" id="day" /> ``` {{EmbedLiveSample("With_semantic_HTML", 50, 50)}} In this case, the only JavaScript needed would be to update the `aria-valuetext` when the input value changes, which really is an optional feature in this case. ## Keyboard interactions | Key(s) | Action | | -------------------- | ------------------------------------------------------------------------------- | | Right and Up arrows | Increase the selected value by one step | | Left and Down arrows | Decrease the selected value by one step | | Page Up | (Optional) Increase the value by a set amount greater than or equal to one step | | Page Down | (Optional) Decrease the value by a set amount greater than or equal to one step | | Home | Set the spinbutton to the minimum value | | End | Set the spinbutton to the maximum value | For the optional <kbd>Page Up</kbd> and <kbd>Page Down</kbd> keys, the change in spinbutton value should preferably be by an amount larger than the step changes made by Up and Down arrow keys. ## Best practices HTML's `<input type="number">` implicitly has the `role` of `spinbutton`. HTML's `<input type="date">` has 3 nested spin buttons, one each for month, day, and year. When using semantic HTML form elements for their intended purposes, do not use `aria-valuemax` or `aria-valuemin` attributes; use `min` and `max` instead. Otherwise, any global `aria-*` attributes and any other `aria-*` attributes are applicable to the `spinbutton` role. ### Prefer semantic HTML It is recommended to use the native {{HTMLElement("input")}} element of type `number`, [`<input type="number">`](/en-US/docs/Web/HTML/Element/input/number), rather than the `spinbutton` role. ## Specifications {{Specifications}} ## See also - [`<input type="number">`](/en-US/docs/Web/HTML/Element/input/number) - [`<input type="date">`](/en-US/docs/Web/HTML/Element/input/date) - [`<input type="time">`](/en-US/docs/Web/HTML/Element/input/time) - Other range widgets include: - [`meter`](/en-US/docs/Web/Accessibility/ARIA/Roles/meter_role) - [`scrollbar`](/en-US/docs/Web/Accessibility/ARIA/Roles/scrollbar_role) - [`separator`](/en-US/docs/Web/Accessibility/ARIA/Roles/separator_role) (if focusable) - [`progressbar`](/en-US/docs/Web/Accessibility/ARIA/Roles/progressbar_role) - [`slider`](/en-US/docs/Web/Accessibility/ARIA/Roles/slider_role) - Working examples: - [Date picker spin button example](https://www.w3.org/WAI/ARIA/apg/patterns/spinbutton/examples/datepicker-spinbuttons/) - [Toolbar example: font-size picker](https://www.w3.org/WAI/ARIA/apg/patterns/toolbar/examples/toolbar/) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/listitem_role/index.md
--- title: "ARIA: listitem role" slug: Web/Accessibility/ARIA/Roles/listitem_role page-type: aria-role spec-urls: https://w3c.github.io/aria/#listitem --- The ARIA `listitem` role can be used to identify an item inside a list of items. It is normally used in conjunction with the [`list`](/en-US/docs/Web/Accessibility/ARIA/Roles/list_role) role, which is used to identify a list container. ```html <section role="list"> <div role="listitem">List item 1</div> <div role="listitem">List item 2</div> <div role="listitem">List item 3</div> </section> ``` ## Description Any content that consists of an outer container with a list of elements inside it can be identified to assistive technologies using the `list` and `listitem` containers respectively. There are no hard and fast rules about which elements you should use to mark up the list and list items, but you should make sure that the list items make sense in the context of a list, e.g. a shopping list, recipe steps, driving directions. > **Note:** If at all possible in your work, you should use the appropriate semantic HTML elements to mark up a list and its listitems — {{HTMLElement("ul")}}/{{HTMLElement("ol")}} and {{HTMLElement("li")}}. See [Best practices](#best_practices) for a full example. ### Associated WAI-ARIA Roles, States, and Properties - [`list`](/en-US/docs/Web/Accessibility/ARIA/Roles/list_role) - : A list of items. Elements with role `list` must have one or more elements with the role `listitem` as children, a one or more elements with the role of `group` that have one or more elements with the `listitem` role as children. - [`group`](/en-US/docs/Web/Accessibility/ARIA/Roles/group_role) - : A collection of related objects, limited to list items when nested in a list, not important enough to have their own place in a pages table of contents. ## Best practices Only use `role="list"` and `role="listitem"` if you have to — for example if you don't have control over your HTML but are able to improve accessibility dynamically after the fact with JavaScript. If at all possible, you should use the appropriate semantic HTML elements to mark up a list and listitems — {{HTMLElement("ol")}}, {{HTMLElement("ul")}} and {{HTMLElement("li")}}. For example, our above example should be rewritten as follows: ```html <ul> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> </ul> ``` or use an ordered list if the order of the list items matters: ```html <ol> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> </ol> ``` > **Note:** The ARIA `list` / `listitem` roles don't distinguish between ordered and unordered lists. > **Note:** Styling a list with `list-style: none;` in CSS removes the list semantics. Adding `role="listitem"` returns the semantics. > **Note:** If you are marking up a list of items that will function as a tabbed interface, you should instead use the [`tab`](/en-US/docs/Web/Accessibility/ARIA/Roles/tab_role), [`tabpanel`](/en-US/docs/Web/Accessibility/ARIA/Roles/tabpanel_role), and [`tablist`](/en-US/docs/Web/Accessibility/ARIA/Roles/tablist_role) roles. ## Specifications {{Specifications}} ## See also - [HTML `<li>` element](/en-US/docs/Web/HTML/Element/li) - [HTML `<ul>` element](/en-US/docs/Web/HTML/Element/ul) - [HTML `<ol>` element](/en-US/docs/Web/HTML/Element/ol) - [ARIA: `list` role](/en-US/docs/Web/Accessibility/ARIA/Roles/list_role) - [ARIA: `group` role](/en-US/docs/Web/Accessibility/ARIA/Roles/group_role) - [Accessibility Object Model](https://wicg.github.io/aom/spec/) - [ARIA in HTML](https://w3c.github.io/html-aria/) - [ARIA Lists examples](https://www.scottohara.me/blog/2018/05/26/aria-lists.html) — by Scott O'Hara <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/switch_role/index.md
--- title: "ARIA: switch role" slug: Web/Accessibility/ARIA/Roles/switch_role page-type: aria-role spec-urls: - https://w3c.github.io/aria/#switch - https://w3c.github.io/html-aria/#index-aria-switch --- The ARIA **`switch`** role is functionally identical to the [checkbox](/en-US/docs/Web/Accessibility/ARIA/Roles/checkbox_role) role, except that instead of representing "checked" and "unchecked" states, which are fairly generic in meaning, the `switch` role represents the states "on" and "off." This example creates a widget and assigns the ARIA `switch` role to it. ```html <button type="button" role="switch" aria-checked="true" id="speakerPower" class="switch"> <span aria-hidden="true">off</span> <span aria-hidden="true">on</span> </button> <label for="speakerPower" class="switch">Speaker power</label> ``` ## Description The ARIA **`switch`** role is identical to the [checkbox](/en-US/docs/Web/Accessibility/ARIA/Roles/checkbox_role) role, except instead of being "checked" or "unchecked", it is either "on" or "off". Like the [checkbox](/en-US/docs/Web/Accessibility/ARIA/Roles/checkbox_role) role, the [`aria-checked`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked) attribute is required. The two possible values are `true` and `false`. Unlike an `<input type="checkbox">` or `role="checkbox"`, there is no `indeterminate` or `mixed` state. The `switch` role does not support the value `mixed` for the `aria-checked` attribute; assigning a value of `mixed` to a `switch` instead sets the value to `false`. Assistive technologies may choose to represent `switch` widgets with a specialized presentation to reflect the notion of an on/off switch. Since a switch is an interactive control, it must be focusable and keyboard accessible. If the role is applied to a non-focusable element, use the `tabindex` attribute to change this. The expected keyboard shortcut for toggling the value of a switch is the <kbd>Space</kbd> key. The developer is required to change the value of the `aria-checked` attribute dynamically when the switch is toggled. ### All descendants are presentational There are some types of user interface components that, when represented in a platform accessibility API, can only contain text. Accessibility APIs do not have a way of representing semantic elements contained in a `switch`. To deal with this limitation, browsers, automatically apply role [`presentation`](/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role) to all descendant elements of any `switch` element as it is a role that does not support semantic children. For example, consider the following `switch` element, which contains a heading. ```html <div role="switch"><h3>Title of my switch</h3></div> ``` Because descendants of `switch` are presentational, the following code is equivalent: ```html <div role="switch"><h3 role="presentation">Title of my switch</h3></div> ``` From the assistive technology user's perspective, the heading does not exist since the previous code snippets are equivalent to the following in the [accessibility tree](/en-US/docs/Glossary/Accessibility_tree): ```html <div role="switch">Title of my switch</div> ``` ### Associated ARIA roles, states, and properties - [`aria-checked`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked) attribute - : The `aria-checked` attribute is **required** when using the `switch` role, as it represents the current state of the widget that the `switch` role is applied to. A value of `true` represents the "on" state; `false` represents the "off" state; a value of `mixed` is not supported by the switch role, and is treated as `false`. The default value is `false`. - [`aria-readonly`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-readonly) attribute - : The `aria-readonly` attribute is supported by the `switch` role. It indicates whether the widget's state is editable by the user. A value of `false` means that the user _can_ change the widget's state; a value of `true` means that the user _cannot_ change the widget's state. The default value is `false`. ### Required JavaScript features - Handler for click events - : When the user clicks on the switch widget, a [click event](/en-US/docs/Web/API/Element/click_event) is fired, which must be handled in order to change the state of the widget. - Changing the `aria-checked` attribute - : When a click event is fired on the switch widget, the handler must change the value of the `aria-checked` attribute from `true` to `false`, or vice versa. ## Possible effects on user agents and assistive technology When the `switch` role is added to an element, the {{Glossary("user agent")}} handles it like this: - The element is exposed to the system's accessibility infrastructure as having the `switch` role. - When the `aria-checked` attribute's value changes, an accessible event is fired using the system's accessibility API if one is available and it supports the `switch` role. - All elements that are descendants of an element with the `switch` role applied to it are automatically assigned role `presentation`. This prevents elements that are used to construct the switch from being interacted with individually by assistive technologies. Text in these elements remains visible to the user agent and may be read or otherwise delivered to the user, unless it's expressly hidden using {{cssxref("display", "display: none")}} or `aria-hidden="true"`. The assistive technology, if it supports the `switch` role, responds by doing the following: - Screen readers should announce the element as a switch, optionally providing instructions as to how to activate the switch. > **Note:** There are varying opinions on how assistive technologies should handle this role; the above is a suggested practice and may differ from other sources. ## Examples The following examples should help you understand how to apply and use the `switch` role. ### Adding the switch role in ARIA This simple example just creates a widget and assigns the ARIA `switch` role to it. The button is styled with an appearance reminiscent of an on/off power switch. #### HTML The HTML is fairly simple here. The switch is implemented as a {{HTMLElement("button")}} element which is initially checked courtesy of its `aria-checked` attribute being set to `"true"`. The switch has two child elements containing the "off" and "on" labels and is followed by a {{HTMLElement("label")}} identifying the switch. ```html <button role="switch" aria-checked="true" id="speakerPower" class="switch"> <span>off</span> <span>on</span> </button> <label for="speakerPower" class="switch">Speaker power</label> ``` #### JavaScript This JavaScript code defines and applies a function to handle click events on switch widgets. The function changes the `aria-checked` attribute from `true` to `false`, or vice versa. ```js document.querySelectorAll(".switch").forEach((theSwitch) => { theSwitch.addEventListener("click", handleClickEvent, false); }); function handleClickEvent(evt) { const el = evt.target; if (el.getAttribute("aria-checked") === "true") { el.setAttribute("aria-checked", "false"); } else { el.setAttribute("aria-checked", "true"); } } ``` #### CSS The purpose of the CSS is to establish a look and feel for the switch that's reminiscent of the power switch paradigm. ```css button.switch { margin: 0; padding: 0; width: 70px; height: 26px; border: 2px solid black; display: inline-block; margin-right: 0.25em; line-height: 20px; vertical-align: middle; text-align: center; font: 12px "Open Sans", "Arial", serif; } button.switch span { padding: 0 4px; pointer-events: none; } [role="switch"][aria-checked="false"] :first-child, [role="switch"][aria-checked="true"] :last-child { background: #262; color: #eef; } [role="switch"][aria-checked="false"] :last-child, [role="switch"][aria-checked="true"] :first-child { color: #bbd; } label.switch { font: 16px "Open Sans", "Arial", sans-serif; line-height: 20px; vertical-align: middle; user-select: none; } ``` The most interesting part is probably the use of attribute selectors and the {{cssxref(":first-child")}} and {{cssxref(":last-child")}} pseudo-classes to do all the heavy lifting of changing the appearance of the switch based on whether it's on or off. #### Result The result looks like this: {{EmbedLiveSample("Adding_the_switch_role_in_ARIA", 600, 40)}} ## Specifications {{Specifications}} ## See also - [ARIA: checkbox role](/en-US/docs/Web/Accessibility/ARIA/Roles/checkbox_role) - [`<input type="checkbox">`](/en-US/docs/Web/HTML/Element/input/checkbox) - [`aria-hidden`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-hidden) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/term_role/index.md
--- title: "ARIA: term role" slug: Web/Accessibility/ARIA/Roles/term_role page-type: aria-role spec-urls: https://w3c.github.io/aria/#term --- The `term` role can be used for a word or phrase with an optional corresponding [`definition`](/en-US/docs/Web/Accessibility/ARIA/Roles/definition_role). ## Description The `term` role can be used for a word or phrase with an optional corresponding [`definition`](/en-US/docs/Web/Accessibility/ARIA/Roles/definition_role). It is equivalent in semantics to the HTML {{HTMLElement('dfn')}} element and the definition term ({{HTMLElement('dt')}}) element within a definition list ({{HTMLElement('dl')}} ). The `term` role is used to explicitly identify a word or phrase for which a definition has been provided by the author or is expected to be provided by the user. If there is an existing definition, or a form or form control to enter a definition, authors SHOULD set [`aria-details`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-details) to point to the related element. Don't use the `role="term"` on interactive elements like links because it can interfere with assistive technology users ability to interact with the element. Also, the term itself is the accessible name, so do not use [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) or [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby). > **Warning:** The accessible name should be the term itself, so DO NOT use `aria-label` or `aria-labelledby`. ### Associated WAI-ARIA roles, states, and properties None. ### Keyboard interactions None. ### Required JavaScript features None. ## Examples ```html <p> <span role="term">Mansplaining</span>, <span role="definition" >a portmanteau of "man" and "explain", is the patronizing act of explaining without being asked to do so, to someone already learned on the topic, often after someone has already explained it</span >. </p> ``` Including better semantics, the above could also be written: ```html <p> <dfn role="term">Mansplaining</dfn>, <span role="definition" >a portmanteau of "man" and "explain", is the patronizing act of explaining without being asked to do so, to someone already learned on the topic, often after someone has already explained it</span >. </p> ``` or without any ARIA (but possibly not how you want it presented) ```html <dl> <dt>Mansplaining</dt> <dd> A portmanteau of "man" and "explain", is the patronizing act of explaining without being asked to do so, to someone already learned on the topic, often after someone has already explained it. </dd> </dl> ``` ## Accessibility concerns Don't use the `role="term"` on interactive elements such as links as it can interfere with the assistive technology user's ability to interact with the element. ## Best Practices Allow the term itself to define the accessible name. Do not use `aria-label` or `aria-labelledby`. ### Prefer HTML ## Specifications {{Specifications}} ## See also - [ARIA: `definition` role](/en-US/docs/Web/Accessibility/ARIA/Roles/definition_role). - The HTML {{HTMLElement('dfn')}} element <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/input_role/index.md
--- title: "ARIA: input role" slug: Web/Accessibility/ARIA/Roles/input_role page-type: aria-role spec-urls: https://w3c.github.io/aria/#input --- The `input` abstract role is a generic type of widget that allows user input. > **Note:** The `input` role is an [abstract role](/en-US/docs/Web/Accessibility/ARIA/Roles#6._abstract_roles). It is included here for completeness of documentation. It is not to be used by web authors. ## Description The `input` role is an abstract role. It must not be used by web authors. It is the superclass for input widgets that provide for user input, including [`checkbox`](/en-US/docs/Web/Accessibility/ARIA/Roles/checkbox_role), [`radio`](/en-US/docs/Web/Accessibility/ARIA/Roles/radio_role), and [`textbox`](/en-US/docs/Web/Accessibility/ARIA/Roles/textbox_role). For all three, consider using the {{HTMLElement("input")}} element of type [`checkbox`](/en-US/docs/Web/HTML/Element/input/checkbox), [`radio`](/en-US/docs/Web/HTML/Element/input/radio) and [`text`](/en-US/docs/Web/HTML/Element/input/text), respectively. ## Best Practices Do not use. ## Specifications {{Specifications}} ## See also - [ARIA: `widget` role](/en-US/docs/Web/Accessibility/ARIA/Roles/widget_role) - [ARIA: `checkbox` role](/en-US/docs/Web/Accessibility/ARIA/Roles/checkbox_role) - [ARIA: `combobox` role](/en-US/docs/Web/Accessibility/ARIA/Roles/combobox_role) - [ARIA: `option` role](/en-US/docs/Web/Accessibility/ARIA/Roles/option_role) - [ARIA: `radio` role](/en-US/docs/Web/Accessibility/ARIA/Roles/radio_role) - [ARIA: `slider` role](/en-US/docs/Web/Accessibility/ARIA/Roles/slider_role) - [ARIA: `spinbutton` role](/en-US/docs/Web/Accessibility/ARIA/Roles/spinbutton_role) - [ARIA: `textbox` role](/en-US/docs/Web/Accessibility/ARIA/Roles/textbox_role) - [HTML: the `input` element](/en-US/docs/Web/HTML/Element/input) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/select_role/index.md
--- title: "ARIA: select role" slug: Web/Accessibility/ARIA/Roles/select_role page-type: aria-role spec-urls: https://w3c.github.io/aria/#select --- The **`select` role**, an abstract role, is superclass role for form widgets that allows the user to make selections from a set of choices. > **Note:** The `select` role is an [abstract role](/en-US/docs/Web/Accessibility/ARIA/Roles#6._abstract_roles). It is included here for completeness of documentation. It **should not be used** by web authors. ## Description The structural `select` role, an abstract role, is superclass role for four form widgets, [`listbox`](/en-US/docs/Web/Accessibility/ARIA/Roles/listbox_role), [`menu`](/en-US/docs/Web/Accessibility/ARIA/Roles/menu_role), [`radiogroup`](/en-US/docs/Web/Accessibility/ARIA/Roles/radiogroup_role), and [`tree`](/en-US/docs/Web/Accessibility/ARIA/Roles/tree_role), which allow users to make selections from a set of choices. ## Best Practices Do not use. ## Specifications {{Specifications}} ## See also - [ARIA: `composite` role](/en-US/docs/Web/Accessibility/ARIA/Roles/composite_role) - [ARIA: `group` role](/en-US/docs/Web/Accessibility/ARIA/Roles/group_role) - [ARIA: `listbox` role](/en-US/docs/Web/Accessibility/ARIA/Roles/listbox_role) - [ARIA: `menu` role](/en-US/docs/Web/Accessibility/ARIA/Roles/menu_role) - [ARIA: `radiogroup` role](/en-US/docs/Web/Accessibility/ARIA/Roles/radiogroup_role) - [ARIA: `tree` role](/en-US/docs/Web/Accessibility/ARIA/Roles/tree_role) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/meter_role/index.md
--- title: "ARIA: meter role" slug: Web/Accessibility/ARIA/Roles/meter_role page-type: aria-role spec-urls: https://www.w3.org/TR/wai-aria-1.2/#meter --- The `meter` role is used to identify an element being used as a meter. > **Note:** Where possible, it is recommended that you use a native {{HTMLElement("meter")}} element rather than the `meter` role, as native elements are more widely supported by user agents and assistive technology. ## Description A meter is a graphical display of a numeric value within a defined range. For example, showing battery percentage. A meter is not appropriate for values that do not have a meaningful maximum limit. Meters should not be used to indicate progress (for example loading), this should be communicated with the {{HTMLElement('progress')}} element. Each element with `role="meter"` must also have one of the following: - An [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) attribute. - An [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) attribute pointing to an element with text that describes the meter. ### All descendants are presentational There are some types of user interface components that, when represented in a platform accessibility API, can only contain text. Accessibility APIs do not have a way of representing semantic elements contained in a `meter`. To deal with this limitation, browsers, automatically apply role [`presentation`](/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role) to all descendant elements of any `meter` element as it is a role that does not support semantic children. For example, consider the following `meter` element, which contains a heading. ```html <div role="meter"><h3>Title of my meter</h3></div> ``` Because descendants of `meter` are presentational, the following code is equivalent: ```html <div role="meter"><h3 role="presentation">Title of my meter</h3></div> ``` From the assistive technology user's perspective, the heading does not exist since the previous code snippets are equivalent to the following in the [accessibility tree](/en-US/docs/Glossary/Accessibility_tree).: ```html <div role="meter">Title of my meter</div> ``` ### Associated ARIA roles, states, and properties - [`aria-valuenow`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuenow) - : Set to a decimal value between `aria-valuemin` and `aria-valuemax` indicating the current value of the meter. - [`aria-valuetext`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuetext) - : Assistive technologies often present the value of `aria-valuenow` as a percentage. If this would not be accurate use this property to make the meter value understandable. - [`aria-valuemin`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemin) - : Set to a decimal value representing the minimum value, and less than `aria-valuemax`. - [`aria-valuemax`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemax) - : Set to a decimal value representing the maximum value, and greater than `aria-valuemin`. It is recommended to use a native {{HTMLElement("meter")}} element rather than the `meter` role. User agents provide a stylize widget for the {{HTMLElement("meter")}} element based on the current `value` as it relates to the `min` and `max` values. When using non-semantic elements, all features of the native semantic element need to be recreated with ARIA attributes, JavaScript and CSS. ## Examples An example of a meter using `role="meter"`: ```html <div role="meter" aria-valuenow="90" aria-valuemin="0" aria-valuemax="100" aria-labelledby="cpu_usage_label"> <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" style="width: 90%"> <rect x="0" y="0" width="100%" height="100%" fill="currentcolor"></rect> </svg> </div> ``` In the above scenario, when the `aria-valuenow` value updates, the width of the SVG also needs to be updated as can be seen in [the W3C working meter example](https://www.w3.org/TR/wai-aria-practices-1.2/examples/meter/meter.html). ## Specifications {{Specifications}} ## See also - {{HTMLElement('meter')}} - {{HTMLElement('progress')}} <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/note_role/index.md
--- title: "ARIA: note role" slug: Web/Accessibility/ARIA/Roles/note_role page-type: aria-role spec-urls: https://w3c.github.io/aria/#note --- A `note` role suggests a section whose content is parenthetic or ancillary to the main content. ## Description The `note` role can be added to parenthetic or ancillary content if no other native element or other role fits the purpose. ### Associated WAI-ARIA roles, states, and properties - [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) or [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) (optional) - : Naming a note is optional, but can help screen reader users understand its context and purpose. The name can be provided using `aria-labelledby` if a visible label is present, otherwise with `aria-label`. ## Examples ```html <h1>Madam C. J. Walker</h1> <p> Madam C.J. Walker was an African American entrepreneur, philanthropist, and political and social activist. </p> <h2>Early Life</h2> … <h2>Career</h2> … <p role="note" class="hilitebox"> At the height of the depression, Madam C. J. Walker trained 20,000 women to sell hair pomade door-to-door </p> <h2>Activism and Philanthropy</h2> … ``` In the above Wikipedia style entry for Madam C.J. Walker, the `hilitebox` with role `note` could have been a {{HTMLElement('blockquote')}} if it contained a quote or {{HTMLElement('figcaption')}} in a {{HTMLElement('figure')}} if there was an associated image. In this case, as neither of those made sense, the `note` role was added to add semantics to the parenthetic content. ## Specifications {{Specifications}} ## See also - [Document structure roles](/en-US/docs/Web/Accessibility/ARIA/Roles#1._document_structure_roles) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/treeitem_role/index.md
--- title: "ARIA: treeitem role" slug: Web/Accessibility/ARIA/Roles/treeitem_role page-type: aria-role spec-urls: - https://w3c.github.io/aria/#treeitem - https://www.w3.org/WAI/ARIA/apg/patterns/treeview/examples/treeview-navigation/ --- A `treeitem` is an item in a `tree`. ## Description A [`tree`](/en-US/docs/Web/Accessibility/ARIA/Roles/tree_role) is a hierarchical list with parent and child nodes that can expand and collapse. A `treeitem` is a node in a `tree`. The root of the tree is `tree`, but all tree nodes are `treeitem` elements, even if they themselves have nested `treeitem` nodes. An example of a `tree` is a file system selection user interface: a tree view displaying folders and files. Each folder and file is a `treeitem`. Folder items, which are `treeitem` elements, can be expanded to reveal the contents of the folder—which may be files, folders, or both, and are all `treeitems`—and collapsed, hiding its contents. In a tree hierarchy, the _root node_ has the role `tree`. All other nodes, other than the root node, have the role of `treeitem`, whether or not they have children. A `treeitem` that is a parent is a **parent node**. A `treeitem` that is not a parent is an _end node_. Tree items that have children can be expanded or collapsed, showing and hiding their children. A parent node that is expanded so its child nodes are visible is an **open node**. A parent node that is collapsed so the child nodes are not visible is a **closed node**. Each parent node contains or owns an element with role [`group`](/en-US/docs/Web/Accessibility/ARIA/Roles/group_role). A parent node is an expandable collection of `treeitem` elements. These child nodes are not direct descendants of the parent node: rather, they should be enclosed in an element with the `group` role. Each parent node should include the [`aria-expanded`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-expanded) attribute. It is set to `false` when closed `true` when open. End nodes should not have the `aria-expanded` attribute included as the presence of the attribute indicates to assistive technologies that the node is a parent. > **Note:** ARIA tree views use navigation more similar to native applications than to web applications and are navigated primarily with arrow keys on the keyboard instead of the <kbd>Tab</kbd>. This form of navigation is not common for most browser content, though normal and expected for native applications. For this reason, consider alternative options to address the functionality you need before creating a tree view. Any element with a `treeitem` role must be nested in, or owned by, an element with role `tree`. Tree items can be a child of `tree`, `treeitem`, or an element with role `group` that is contained in, or owned by, an element with role `tree` or `treeitem`. If a `treeitem` is not nested within a `tree`, or nested in a `group` that is owned by a `tree`, include the [`id`](/en-US/docs/Web/HTML/Global_attributes#id) of the `treeitem` in the [`aria-owns`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-owns) attribute value on the owning `tree`, `treeitem` or `group` element. Trees can be "single-select", allowing users to choose just one `treeitem` for an action, or "multi-select", where users are able to select more than one `treeitem` nodes for an action. In both cases, to be keyboard accessible, focus must be managed for all tree descendants. In single-select trees, only one treeitem can have [`aria-selected`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-selected) (or [`aria-checked`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked)) set to `true`. When a single-select tree receives focus, if no `treeitem` is selected before the tree receives focus, focus is set on the first `treeitem`. If a `treeitem` is selected before the tree receives focus, focus is set on the single `treeitem` that has `aria-selected="true"` set. All nodes that are selectable but not selected have either `aria-selected` or `aria-checked` set to `false`. If the tree contains nodes that are not selectable, do not include either `aria-selected` or `aria-checked`, as the presence of either attribute indicates to assistive technologies the node is selectable. No more than one node can be selected at a time unless the `tree` node has [`aria-multiselectable="true"`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-multiselectable) set. When a multi-select tree receives focus, if none of the tree items are selected before the tree receives focus, focus is set on the first `treeitem`. If one or more tree items are selected before the tree receives focus, focus is set on the first selected `treeitem`. In multi-select trees, all selected tree items have either `aria-selected="true"` (or `aria-checked="true"`) set. All tree item nodes that are selectable but not currently selected should have `aria-selected="false"` (or `aria-checked="false"`) set. Either `aria-selected` or `aria-checked` can be used to indicate selection for `treeitem` elements. Some user interfaces indicate selection with `aria-selected` in single-select trees and with `aria-checked` in multi-select trees. Using both `aria-selected` and `aria-checked` in the same `tree` is strongly discouraged. Don't use both `aria-selected` and `aria-checked` on treeitems in a single tree unless the meaning and purpose of `aria-selected` is different from the meaning and purpose of `aria-checked`, the meaning and purpose of each state apparent, and the user interface provides a separate method for controlling each state. In multi-select trees, the selected state should be independent of the focus. For example, in a typical file system navigator, the user can move focus to select any number of files for an action, such as copy or move. The visual design should make it clear which items are selected and which item has focus. If the complete set of available treeitems is not present in the DOM due to dynamic loading as the user moves focus in or scrolls the tree, each `treeitem` should have [`aria-level`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-level), [`aria-setsize`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-setsize), and [`aria-posinset`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-posinset) specified. A `treeitem` is required to have an accessible name. Generally, that name comes from the `treeitem`'s contents. The accessible name can also be set via [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) or [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby). ### Associated WAI-ARIA roles, states, and properties - [`tree`](/en-US/docs/Web/Accessibility/ARIA/Roles/tree_role) role - : The root node for the hierarchical list of parent and child `treeitem` nodes that can expand and collapse - [`group`](/en-US/docs/Web/Accessibility/ARIA/Roles/group_role) role - : Identifies a set of `treeitem` child nodes. - [`aria-expanded`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-expanded) - : Set on the root `tree` and on `group` nodes that are parents of `treeitem` nodes, to indicate whether the tree view is expanded (`true`) or collapsed (`false`). - [`aria-selected`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-selected) - : Set to `true` or `false`, indicates a `treeitem` is selectable, and whether or not it is currently selected. - [`aria-checked`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked) - : Set to `true` or `false`, indicates the `treeitem` can be checked, and whether or not it is currently checked. ### Keyboard interactions For a vertically oriented `tree`, which is the default orientation: <table> <tr> <td><kbd>Right arrow</kbd></td> <td> <ul> <li>When focus is on a closed node, opens the node; focus does not move. <li>When focus is on an open node, moves focus to the first child node. <li>When focus is on an end node (a tree item with no children), does nothing. </td> </tr> <tr> <td><kbd>Left arrow</kbd></td> <td> <ul> <li>When focus is on an open node, closes the node. <li>When focus is on a child node that is also either an end node or a closed node, moves focus to its parent node. <li>When focus is on a closed `tree`, does nothing. </td> </tr> <tr> <td><kbd>Down Arrow</kbd></td> <td> Moves focus to the next node that is focusable without opening or closing a node. </td> </tr> <tr> <td><kbd>Up Arrow</kbd></td> <td> Moves focus to the previous node that is focusable without opening or closing a node. </td> </tr> <tr> <td><kbd>Home</kbd></td> <td> Moves focus to the first node in the tree without opening or closing a node. </td> </tr> <tr> <td><kbd>End</kbd></td> <td> Moves focus to the last node in the tree that is focusable without opening the node. </td> </tr> <tr> <td><kbd>Enter</kbd></td> <td>Performs the default action of the currently focused node. For parent nodes, it opens or closes the node. In single-select trees, if the node has no children, selects the current node if not already selected (which is the default action). </td> </tr> <tr> <td>Type a character*</td> <td> <ul> <li>Focus moves to the next node with a name that starts with the typed character. <li>If multiple characters are typed in rapid succession, focus moves to the next node with a name that starts with the string of characters typed. </td> </tr> <tr> <td> <kbd>*</kbd> (Optional)</td> <td> Expands all siblings that are at the same level as the current node. </td> </tr> </table> \* Type-ahead is recommended for all trees, especially for trees with more than 7 root nodes ### Multi-select keyboard interactions There are two interaction models for multi-select trees: While you can require that users press a modifier key, such as <kbd>Shift</kbd> or <kbd>Control</kbd> while navigating the list in order to avoid losing selection states, the model that does not require the user to hold a modifier key is recommended. #### Recommended multi user select model <table> <tr> <td><kbd>Space</kbd></td> <td> Toggles the selection state of the focused node. </td> </tr> <tr> <td><kbd>Shift + Down Arrow</kbd> (Optional)</td> <td> Moves focus to and toggles the selection state of the next node. </td> </tr> <tr> <td><kbd>Shift + Up Arrow</kbd> (Optional)</td> <td> Moves focus to and toggles the selection state of the previous node. </td> </tr> <tr> <td><kbd>Shift + Space</kbd> (Optional)</td> <td> Selects contiguous nodes from the most recently selected node to the current node. </td> </tr> <tr> <td><kbd>Control + Shift + Home</kbd> (Optional)</td> <td> Selects the node with focus and all nodes up to the first node. Optionally, moves focus to the first node. </td> </tr> <tr> <td><kbd>Control + Shift + End</kbd> (Optional)</td> <td> Selects the node with focus and all nodes down to the last node. Optionally, moves focus to the last node. </td> </tr> <tr> <td><kbd>Control + A</kbd> (Optional)</td> <td> Selects all nodes in the tree. Optionally, if all nodes are selected, it can also unselect all nodes.</td> </tr> </table> ## Examples The following is how one might mark up a directory listing of web development courses as a tree view: ```html <div> <h3 id="treeLabel">Developer Learning Path</h3> <ul role="tree" aria-labelledby="treeLabel"> <li role="treeitem" aria-expanded="true"> <span>Web</span> <ul role="group"> <li role="treeitem" aria-expanded="false"> <span>Languages</span> <ul role="group"> <li role="treeitem" aria-expanded="false"> <span>HTML</span> <ul role="group"> <li role="treeitem">Document structure</li> <li role="treeitem">Head elements</li> <li role="treeitem">Semantic elements</li> <li role="treeitem">Attributes</li> <li role="treeitem">Web forms</li> </ul> </li> <li role="treeitem">CSS</li> <li role="treeitem">JavaScript</li> </ul> </li> <li role="treeitem" aria-expanded="false"> <span>Accessibility</span> <ul role="group"> <li role="treeitem" aria-label="accessibility object model">AOM</li> <li role="treeitem">WCAG</li> <li role="treeitem">ARIA</li> </ul> </li> <li role="treeitem" aria-expanded="false"> <span>Web Performance</span> <ul role="group"> <li role="treeitem">Load time</li> </ul> </li> <li role="treeitem">APIs</li> </ul> </li> </ul> </div> ``` The above provides the semantics for a tree view, but does not provide any of the interactivity. That must be added in with JavaScript. If the tree items aren't by default focusable, JavaScript can be used [`tabIndex="-1"`](/en-US/docs/Web/HTML/Global_attributes/tabindex) to all the treeitems except the one that should receive focus when the user tabs into the tree which should be set to `tabIndex="0"`. All the keyboard functionality in Keyboard interactions and all pointer events need to be programmed, including focus management, going up and down the tree, expanding and collapsing parent nodes, and selection management. If the tree has more than 7 tree items, including type ahead functionality is recommended. ## Specifications {{Specifications}} ## See also <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/menuitemcheckbox_role/index.md
--- title: "ARIA: menuitemcheckbox role" slug: Web/Accessibility/ARIA/Roles/menuitemcheckbox_role page-type: aria-role spec-urls: - https://w3c.github.io/aria/#menuitemcheckbox - https://www.w3.org/WAI/ARIA/apg/patterns/menubar/examples/menubar-navigation/ --- A `menuitemcheckbox` is a `menuitem` with a checkable state whose possible values are `true`, `false`, or `mixed`. ## Description The items in menu and menubars are menu items. There are three types of menu items: [`menuitem`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitem_role), [`menuitemradio`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemradio_role), and `menuitemcheckbox`. These three elements can only be contained in, or owned by, an element with role [`menu`](/en-US/docs/Web/Accessibility/ARIA/Roles/menu_role) or [`menubar`](/en-US/docs/Web/Accessibility/ARIA/Roles/menubar_role), optionally nested within a grouping element with role of [`group`](/en-US/docs/Web/Accessibility/ARIA/Roles/group_role). Being nested or otherwise owned (see [`aria-owns`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-owns)) in a `menu` or `menubar` identifies the menu items as being related widgets. Menu items, including `menuitemcheckbox` elements, may be grouped within `group` elements or separated by elements with the [`separator`](/en-US/docs/Web/Accessibility/ARIA/Roles/separator_role) role or other equivalent native role such as {{HTMLElement('fieldset')}} and {{HTMLElement('hr')}}. Menu items containing the role of `menuitemcheckbox` must include the [`aria-checked`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked) attribute to expose the checkbox's state to assistive technology, unless using [`<input type="checkbox">`](/en-US/docs/Web/HTML/Element/input/checkbox), in which case the ['checked'](/en-US/docs/Web/HTML/Element/input/checkbox#checked) attribute should be used. Similar to the 'checked' attribute of {{HTMLElement('input')}}s of type `checkbox`, the `aria-checked` attribute of a `menuitemcheckbox` indicates whether the menu item is checked (`true`), unchecked (`false`), or represents a sub-level menu of other menu items that have a mixture of checked and unchecked values (`mixed`). The `mixed` value is similar to the checkbox's [`indeterminate`](/en-US/docs/Web/HTML/Element/input/checkbox#indeterminate_state_checkboxes) attribute, which gives the appearance of a third, neither checked nor unchecked, state. If missing, the value defaults to `false`. An accessible name is required. Ideally, the accessible name should come from an associated {{htmlelement('label')}} element if using `<input type="checkbox">` or visible, descendant content. Realize if the label or descendant content is not sufficient and, preferably, [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) is used referencing non-descendant content or [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) is used, these two ARIA properties will hide other descendant content from assistive technologies. If all elements in the set are not present in the DOM include the [`aria-setsize`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-setsize) and [`aria-posinset`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-posinset) properties. When specifying `aria-setsize` and `aria-posinset` on a `menuitemcheckbox`, set the value with respect to the total number of items in the menu, excluding any separators. The `menuitemcheckbox` element can have phrasing content, but can not have interactive content as descendants and no descendants with a `tabindex` attribute specified. ### All descendants are presentational There are some types of user interface components that, when represented in a platform accessibility API, can only contain text. Accessibility APIs do not have a way of representing semantic elements contained in a `menuitemcheckbox`. To deal with this limitation, browsers, automatically apply role [`presentation`](/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role) to all descendant elements of any `menuitemcheckbox` element as it is a role that does not support semantic children. For example, consider the following `menuitemcheckbox` element, which contains a heading. ```html <div role="menuitemcheckbox"><h6>Name of my checkbox</h6></li> ``` Because descendants of `menuitemcheckbox` are presentational, the following code is equivalent: ```html <div role="menuitemcheckbox"><h6 role="presentation">Name of my checkbox</h6></li> ``` From the assistive technology user's perspective, the heading does not exist since the previous code snippets are equivalent to the following in the [accessibility tree](/en-US/docs/Glossary/Accessibility_tree): ```html <div role="menuitemcheckbox">Name of my checkbox</div> ``` ### Associated WAI-ARIA roles, states, and properties - [`menu`](/en-US/docs/Web/Accessibility/ARIA/Roles/menu_role) role - : Widget that offers a list of common actions or functions the user can invoke. - [`menubar`](/en-US/docs/Web/Accessibility/ARIA/Roles/menubar_role) role - : Similar to `menu` for a consistent set of frequently used commands remaining visible and usually presented horizontally. - [`group`](/en-US/docs/Web/Accessibility/ARIA/Roles/group_role) role - : Container for a group of `menuitem` elements, including `menuitemcheckbox` elements within a `menu` or `menubar`. - [`aria-checked`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked) (Required) - : Set to `true`, `false`, or `mixed`, it indicates the current "checked" state of the menuitemcheckbox ### Keyboard interactions When a `menu` opens, or when a `menubar` receives focus, keyboard focus is placed on the first item. All items in both are focusable, including all `menuitemcheckbox` elements. If the `menuitemcheckbox` is in a submenu in a `menubar` or a menu opened with a menu button, the following keyboard interactions must be programmed in. : - <kbd>Enter</kbd> - : Toggles the `aria-checked` state of the `menuitemcheckbox` and closes the menu. - <kbd>Space</kbd> - : Toggles the `aria-checked` state of the `menuitemcheckbox`. Does not close the menu. - <kbd>Escape</kbd> - : Closes menu. In menubar, moves focus to parent menubar item. - <kbd>Right Arrow</kbd> - : Closes submenu. In menubar, moves focus to next item in the menubar, opening any submenu if there is one. - <kbd>Left Arrow</kbd> - : Closes menu. In menubar, moves focus to previous item in the menubar, opening any submenu if there is one. - <kbd>Down Arrow</kbd> - : Moves focus to the next item in the menu. If focus is on the last item, moves focus to the first item. - <kbd>Up Arrow</kbd> - : Moves focus to previous item in the menu. If focus is on the first item, moves focus to the last item. - <kbd>Home</kbd> - : Moves focus to the first item in the menu. - <kbd>End</kbd> - : Moves focus to the last item in the menu. - <kbd>Character</kbd> - : Moves focus to the next item having a name that starts with the typed character. If none of the items have a name starting with the typed character, focus does not move. ### Required JavaScript #### Required event handlers - `onclick` - : Handle mouse clicks on both the checkbox and the associated label that will change the state of the checkbox by changing the value of the `aria-checked` attribute and the appearance of the checkbox so it appears checked or unchecked to the sighted user - `onKeyDown` - : Handle the case where the user presses the <kbd>Space</kbd> key to change the state of the checkbox by changing the value of the `aria-checked` attribute and the appearance of the checkbox so it appears checked or unchecked to the sighted user. Also handles all keys listed in the keyboard navigation section above. ## Examples ```html <li role="menuitemcheckbox" tabindex="-1" aria-checked="false">Purple</li> ``` The [`tabindex="-1"`](/en-US/docs/Web/HTML/Global_attributes/tabindex) makes the `menuitemcheckbox` focusable but not part of the page tab sequence. Had we included `aria-checked="true"` it would have indicated that the `menuitemcheckbox` was checked, and we would have visually styled the selected state to look checked using the attribute selector `[role='menuitemcheckbox'][aria-checked='true']`. Instead, the presence of `aria-checked="false"` indicates to assistive technologies that the `menuitemcheckbox` is checkable but not currently checked. The accessible name "purple" comes from the contents. The visual appearance of the selected state is a checked checkbox which we can create using [generated content](/en-US/docs/Web/CSS/CSS_generated_content), making it visible and the same color as the content by synchronizing with the `aria-checked` value using CSS [attribute selectors](/en-US/docs/Web/CSS/Attribute_selectors) and [inheriting](/en-US/docs/Web/CSS/inherit) the color. ```css [role="menuitemcheckbox"]::before { display: inline-block; content: ""; color: transparent; width: 1em; text-align: center; outline: 1px solid; margin-inline-end: 2px; font-family: sans-serif; } [role="menuitemcheckbox"][aria-checked="true"]::before { color: inherit; content: "X"; } ``` ### Prefer HTML The first rule of ARIA is: if a native HTML element or attribute has the semantics and behavior you require, use it instead of re-purposing an element and adding an ARIA role, state or property to make it accessible. As such, it is recommended to use the native [HTML checkbox](/en-US/docs/Web/HTML/Element/input/checkbox) form control instead of recreating a checkbox's functionality with JavaScript and ARIA. ## Specifications {{Specifications}} ## See also - [`menuitemradio` role](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemradio_role) - [`checkbox` role](/en-US/docs/Web/Accessibility/ARIA/Roles/checkbox_role) - [`<input type="checkbox">`](/en-US/docs/Web/HTML/Element/input/checkbox) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/img_role/index.md
--- title: "ARIA: img role" slug: Web/Accessibility/ARIA/Roles/img_role page-type: aria-role spec-urls: https://w3c.github.io/aria/#img --- The ARIA `img` role can be used to identify multiple elements inside page content that should be considered as a single image. These elements could be images, code snippets, text, emojis, or other content that can be combined to deliver information in a visual manner. ```html <div role="img" aria-label="Description of the overall image"> <img src="graphic1.png" alt="" /> <img src="graphic2.png" /> </div> ``` ## Description Any set of content that should be consumed as a single image (which could include images, video, audio, code snippets, emojis, or other content) can be identified using `role="img"`. You shouldn't count on the alt text of individual images for conveying context to assistive technologies; most screen readers will consider the element with `role="img"` set on it to be like a black box, and not access the individual elements inside it. Therefore, provide a comprehensive overall descriptive alt text for image, either in the surrounding text, or by using an [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) attribute, with `alt` attributes for search engines or sighted users to be written to the page should an image fail: ```html <div role="img" aria-label="Description of the overall image"> <img src="graphic1.png" alt="alternative text" /> <img src="graphic2.png" alt="in case the images don't load" /> </div> ``` If you wish to add a caption or label to your image that is visible on the page, you can do using: - [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) when the text is a concise label. - [`aria-describedby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby) when the text is a longer description. For example: ```html <div role="img" aria-labelledby="image-1"> … <p id="image-1">Text that describes the group of images.</p> </div> ``` If an image is purely presentational, consider using the [`presentation`](/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role) role. ### SVG and role="img" If you are using embedded SVG images in your page, it is a good idea to set `role="img"` on the outer {{SVGElement('svg')}} element and give it a label. This will cause screen readers to just consider it as a single entity and describe it using the label, rather than trying to read out all the child nodes: ```html <svg role="img" aria-label="Description of your SVG image"> <!-- contents of the SVG image --> </svg> ``` ### Using role="img" to confer meaning that is obscured or implied In certain cases, assistive technology users won't be able to get the meaning of content expressed in certain ways, through certain media, or implied in certain ways. This is obvious to fix in the case of images (you can use the `alt` attribute), but in the case of mixed or other certain types of content it is not so obvious, and `role="img"` can come into play. For example, if you use emojis in your text, the meaning might be obvious to a sighted user, but someone using a screen reader might get confused because the emojis might have either no text representation at all, or the alternative text might be confusing and not match the context it is being used in. For example, take the following code: ```html <div role="img" aria-label="That cat is so cute"> <p>&#x1F408; &#x1F602;</p> </div> ``` `&#x1F408; &#x1F602;`, 🐈 and 😂, are entity references for emojis read out as "Cat" and "Face with tears of joy", but this doesn't necessarily make sense — the implied meaning is possibly more like "That cat is so cute", so we include that in an `aria-label` along with `role="img"`. This seems to work OK across some browser/screen reader combinations, but some of them end up reading the label out twice. Use with caution and test thoroughly. Another example where this might be suitable is when using {{Glossary("ASCII")}} emoji combinations, like the legendary "Table flip": ```html <div role="img" aria-label="Table flip"> <p>(╯°□°)╯︵ ┻━┻</p> </div> ``` If `aria-labelledby` were used, the screen reader would read it. In this case, only the contents of the `aria-label` are announced to screen reader users, hiding the gibberish of the characters without the need for descendant ARIA to hide things, but also hiding potential content that may be part of the image. ### All descendants are presentational There are some types of user interface components that, when represented in a platform accessibility API, can only contain text. Accessibility APIs do not have a way of representing semantic elements contained in an `img`. To deal with this limitation, browsers, automatically apply role [`presentation`](/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role) to all descendant elements of any `img` element as it is a role that does not support semantic children. For example, consider the following `img` element, which contains a heading. ```html <div role="img"><h3>Title of my image</h3></div> ``` Because descendants of `img` are presentational, the following code is equivalent: ```html <div role="img"><h3 role="presentation">Title of my image</h3></div> ``` From the assistive technology user's perspective, the heading does not exist since the previous code snippets are equivalent to the following in the [accessibility tree](/en-US/docs/Glossary/Accessibility_tree).: ```html <div role="img">Title of my image</div> ``` ### Associated WAI-ARIA Roles, States, and Properties - `aria-label` or `aria-labelledby` - : An accessible name is required. For the HTML {{HTMLElement('img')}} element, use the `alt` attribute. For all other elements with the `img` role, use `aria-labelledby` if a visible label is present, otherwise use `aria-label`. ## Examples ```html <span role="img" aria-label="Rating: 4 out of 5 stars"> <span>★</span> <span>★</span> <span>★</span> <span>★</span> <span>☆</span> </span> ``` ## Specifications {{Specifications}} ## See also - The {{HTMLElement('img')}} element - The {{SVGElement('svg')}} element - The {{HTMLElement('picture')}} element - The {{HTMLElement('audio')}} element - The {{HTMLElement('video')}} element - [ARIA: `presentation` role](/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role) - [Accessibility Object Model](https://wicg.github.io/aom/spec/) - [ARIA in HTML](https://w3c.github.io/html-aria/) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/navigation_role/index.md
--- title: "ARIA: navigation role" slug: Web/Accessibility/ARIA/Roles/navigation_role page-type: aria-role spec-urls: - https://w3c.github.io/aria/#navigation - https://www.w3.org/WAI/ARIA/apg/patterns/landmarks/examples/navigation.html --- The `navigation` role is used to identify major groups of links used for navigating through a website or page content. ```html <div role="navigation" aria-label="Main"> <!-- list of links to main website locations --> </div> ``` This is a website's main navigation. ## Description The `navigation` role is [a landmark](/en-US/docs/Web/Accessibility/ARIA/Roles#3._landmark_roles) role. Landmark roles provide a way to identify the organization and structure of a web page. By classifying and labeling sections of a page, structural information conveyed visually through layout is represented programmatically. Screen readers use landmark roles to provide keyboard navigation to important sections of a page. Like the HTML {{HTMLElement('nav')}} element, navigation landmarks provide a way to identify groups (e.g. lists) of links that are intended to be used for website or page content navigation. If a page includes more than one navigation landmark, each should have a unique label. If two or more navigational landmark on a page have the same set of links, use the same label for each. It is preferable to use the HTML5 [`<nav>` element](/en-US/docs/Web/HTML/Element/nav) to define a navigation landmark. If the HTML5 nav element technique is not being used, use a `role="navigation"` attribute to define a navigation landmark. > **Note:** Using the {{HTMLElement('nav')}} element will automatically communicate a section has a role of `navigation`. Developers should always prefer using the correct semantic HTML element over using ARIA ### Associated WAI-ARIA Roles, States, and Properties - [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) - : A brief description of the purpose of the navigation, omitting the term "navigation", as the screen reader will read both the role and the contents of the label. ### Keyboard Interactions None. ### Required JavaScript features None. ## Examples ```html <div role="navigation" aria-label="Customer service"> <ul> <li><a href="#">Help</a></li> <li><a href="#">Order tracking</a></li> <li><a href="#">Shipping &amp; Delivery</a></li> <li><a href="#">Returns</a></li> <li><a href="#">Contact us</a></li> <li><a href="#">Find a store</a></li> </ul> </div> ``` ## Accessibility concerns [Landmark roles](/en-US/docs/Web/Accessibility/ARIA/Roles#3._landmark_roles) are intended to be used sparingly, to identify larger overall sections of the document. Using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page. ## Best practices ### Prefer HTML Using the {{HTMLElement('nav')}} element will automatically communicate a section has a role of `navigation`. If at all possible, prefer using it instead. ### Labeling landmarks #### Multiple landmarks If there is more than one `navigation` landmark role or {{HTMLElement('nav')}} element in a document, provide a label for each landmark. This label will allow an assistive technology user to be able to quickly understand the purpose of each landmark. ```html <div id="main-nav" role="navigation" aria-label="Main"> <!-- content --> </div> … <nav id="footer-nav" aria-label="Footer"> <!-- content --> </nav> ``` #### Repeated landmarks If a `navigation` landmark role or {{HTMLElement('nav')}} element in a document is repeated in a document, and both landmarks have identical content, use the same label for each landmark. An example of this would be repeating the main navigation at the top and bottom of the page. ```html <header> <nav id="main-nav" aria-label="Main"> <!-- list of links to main website locations --> </nav> </header> … <footer> <nav id="footer-nav" aria-label="Main"> <!-- list of links to main website locations --> </nav> </footer> ``` #### Redundant descriptions Screen readers will announce the type of role the landmark is. Because of this, you do not need to describe what the landmark is in its label. For example, a declaration of `role="navigation"` with an of `aria-label="Primary navigation"` may be announced redundantly as, "primary navigation navigation". ## Specifications {{Specifications}} ## See also - The {{HTMLElement('nav')}} element - [Using HTML sections and outlines](/en-US/docs/Web/HTML/Element/Heading_Elements) - [Using WAI-ARIA Landmarks – 2013 | The Paciello Group](https://www.tpgi.com/using-wai-aria-landmarks-2013/) - [Accessible Landmarks | scottohara.me](https://www.scottohara.me/blog/2018/03/03/landmarks.html) - [Semantic navigation with the nav element | HTML5 Doctor](https://html5doctor.com/nav-element/) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/rowheader_role/index.md
--- title: "ARIA: rowheader role" slug: Web/Accessibility/ARIA/Roles/rowheader_role page-type: aria-role spec-urls: https://w3c.github.io/aria/#rowheader --- An element with `role="rowheader"` is a [cell](/en-US/docs/Web/Accessibility/ARIA/Roles/cell_role) containing header information for a [row](/en-US/docs/Web/Accessibility/ARIA/Roles/row_role) within a tabular structure of a [`grid`](/en-US/docs/Web/Accessibility/ARIA/Roles/grid_role), [`table`](/en-US/docs/Web/Accessibility/ARIA/Roles/table_role) or [`treegrid`](/en-US/docs/Web/Accessibility/ARIA/Roles/treegrid_role). ## Description `Rowheader` is the header [`cell`](/en-US/docs/Web/Accessibility/ARIA/Roles/cell_role) for a row, establishing a relationship between it and the other cells in the same [`row`](/en-US/docs/Web/Accessibility/ARIA/Roles/row_role). ```html <div role="table" aria-label="Populations" aria-describedby="country_population_desc"> <div id="country_population_desc">World Populations by Country</div> <div role="rowgroup"> <div role="row"> <span role="columnheader" aria-sort="descending">Country</span> <span role="columnheader" aria-sort="none">Population</span> </div> </div> <div role="rowgroup"> <div role="row"> <span role="rowheader">Finland</span> <span role="cell">5.5 million</span> </div> <div role="row"> <span role="rowheader">France</span> <span role="cell">67 million</span> </div> </div> </div> ``` It is a structural equivalent to the {{HTMLElement('th')}} element with a scope of `row`, `<th scope="row">`. Using the native {{HTMLElement('th')}} HTML element is strongly encouraged. To create an ARIA row header, add `role="rowheader"` to the element. That row header must be nested within a `row`, which, in turn, is nested within a `rowgroup`, or directly within a `grid`, `table` or `treegrid`. > **Note:** Using the native [table elements](/en-US/docs/Learn/HTML/Tables/Basics) whenever possible, is strongly encouraged. ### Associated WAI-ARIA roles, states, and properties #### Context roles - [role="row"](/en-US/docs/Web/Accessibility/ARIA/Roles/row_role) - : The only context in which you will find a row. It encompasses a cell or group of cells row, of which only one should be of rowheader type. Similar to the native {{HTMLElement('tr')}} HTML element. ### Keyboard interactions None ### Required JavaScript features None. > **Note:** The first rule of ARIA use is if you can use a native feature with the semantics and behavior you require already built in, instead of re-purposing an element and **adding** an ARIA role, state or property to make it accessible, then do so. Employ the HTML `<table>`, `<tr>`, `<th>`, `<td>`, and other [table elements](/en-US/docs/Learn/HTML/Tables/Basics) instead of the ARIA table roles whenever possible. ## Examples ```html <div role="table" aria-label="Semantic Elements" aria-describedby="semantic_elements_table_desc" aria-rowcount="81"> <div id="semantic_elements_table_desc"> Semantic Elements to use instead of ARIA's roles </div> <div role="rowgroup"> <div role="row"> <span role="columnheader" aria-sort="none">ARIA Role</span> <span role="columnheader" aria-sort="none">Semantic Element</span> </div> </div> <div role="rowgroup"> <div role="row" aria-rowindex="11"> <span role="rowheader">header</span> <span role="cell">h1</span> </div> <div role="row" aria-rowindex="16"> <span role="rowheader">header</span> <span role="cell">h6</span> </div> <div role="row" aria-rowindex="18"> <span role="rowheader">rowgroup</span> <span role="cell">thead</span> </div> <div role="row" aria-rowindex="24"> <span role="rowheader">term</span> <span role="cell">dt</span> </div> </div> </div> ``` The above is a non-semantic ARIA table with a table header and table body, with five of 81 rows present in the DOM: one within a table header and four rows within the table body. The header row, alone in a header rowgroup, has two column headers. The columns are sortable, but not currently sorted, as indicated by the [`aria-sort`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-sort) property. The table body is a separate rowgroup, with four rows currently in the DOM. Each data table row has a row header. Because not all the rows are in the DOM, we've included the [`aria-rowindex`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowindex) property on every row. ## Best practices Only use {{HTMLElement('table')}}, {{HTMLElement('tbody')}}, {{HTMLElement('thead')}}, {{HTMLElement('tr')}}, {{HTMLElement('th')}}, {{HTMLElement('td')}}, and so on for data table structure. You can add these ARIA roles to ensure accessibility should the native semantics of the table be removed, such as with CSS. A relevant use case for all the ARIA table roles is when the CSS's `display` property overrides the native semantics of a table, such as by `display: grid`. In this case, you can use the ARIA table roles to add in the semantics. ```html <table role="table" aria-label="Semantic Elements" aria-describedby="semantic_elements_table_desc" aria-rowcount="81"> <caption id="semantic_elements_table_desc"> Semantic Elements to use instead of ARIA's roles </caption> <thead role="rowgroup"> <tr role="row"> <th role="columnheader" aria-sort="none">ARIA Role</th> <th role="columnheader" aria-sort="none">Semantic Element</th> </tr> </thead> <tbody role="rowgroup"> <tr role="row" aria-rowindex="11"> <th role="rowheader">header</th> <td role="cell">h1</td> </tr> <tr role="row" aria-rowindex="16"> <th role="rowheader">header</th> <td role="cell">h6</td> </tr> </tbody> </table> ``` Above is the semantic way of writing a table. The ARIA roles are only necessary if the native semantics of the table, and therefore the table row headers, are obliterated, such as by setting the [display property to flex or grid](/en-US/docs/Web/CSS/display#accessibility_concerns). ### Added benefits none ## Specifications {{Specifications}} ## See also - [The HTML `<table>` element](/en-US/docs/Web/HTML/Element/table) - [The HTML `<th>` element](/en-US/docs/Web/HTML/Element/th) - [HTML table tutorial](/en-US/docs/Learn/HTML/Tables/Basics) - [ARIA `cell` role](/en-US/docs/Web/Accessibility/ARIA/Roles/cell_role) - [ARIA `row` role](/en-US/docs/Web/Accessibility/ARIA/Roles/row_role) - [ARIA `gridcell` role](/en-US/docs/Web/Accessibility/ARIA/Roles/gridcell_role) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/table_role/index.md
--- title: "ARIA: table role" slug: Web/Accessibility/ARIA/Roles/table_role page-type: aria-role spec-urls: - https://w3c.github.io/aria/#table - https://www.w3.org/WAI/ARIA/apg/patterns/table/examples/table/ --- The `table` value of the ARIA `role` attribute identifies the element containing the role as having a non-interactive table structure containing data arranged in rows and columns, similar to the native {{HTMLElement('table')}} HTML element. ```html <div role="table" aria-label="Semantic Elements" aria-describedby="semantic_elements_table_desc" aria-rowcount="81"> <div id="semantic_elements_table_desc"> Semantic Elements to use instead of ARIA's roles </div> <div role="rowgroup"> <div role="row"> <span role="columnheader" aria-sort="none">ARIA Role</span> <span role="columnheader" aria-sort="none">Semantic Element</span> </div> </div> <div role="rowgroup"> <div role="row" aria-rowindex="11"> <span role="cell">header</span> <span role="cell">h1</span> </div> <div role="row" aria-rowindex="16"> <span role="cell">header</span> <span role="cell">h6</span> </div> <div role="row" aria-rowindex="18"> <span role="cell">rowgroup</span> <span role="cell">thead</span> </div> <div role="row" aria-rowindex="24"> <span role="cell">term</span> <span role="cell">dt</span> </div> </div> </div> ``` ## Description An element with `role="table"` is a static tabular structure with rows containing cells. The cells are not focusable or selectable, though widgets within individual cells of the table can be interactive. Using a native HTML {{HTMLElement('table')}} element whenever possible is strongly encouraged. > **Warning:** If a table maintains a selection state, has two-dimensional navigation, or allows the user to rearrange cell order use [`grid`](/en-US/docs/Web/Accessibility/ARIA/Roles/grid_role) or [`treegrid`](/en-US/docs/Web/Accessibility/ARIA/Roles/treegrid_role) instead. To create an ARIA table, add `role="table"` to the container element. Within that container, each row has `role="row"` set and contains child cells. Each cell has a role of either `columnheader`, `rowheader`, or `cell`. Rows can be children of the table or within a `rowgroup`. The table caption can be defined via [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) or [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label). All other semantic table elements, such as {{HTMLElement('tbody')}}, {{HTMLElement('thead')}}, {{HTMLElement('tr')}}, {{HTMLElement('th')}}, and {{HTMLElement('td')}}, need to be added via associated roles, such as `rowgroup`, `row`, `columnheader`, and `cell`. If the table contains sortable columns or rows, the [`aria-sort`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-sort) attribute should be added on the header cell element (not the table itself). If any rows or columns are hidden, the [`aria-colcount`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colcount) or [`aria-rowcount`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowcount) should be included indicating the total number of columns or rows, respectively, along with the [`aria-colindex`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colindex) or [`aria-rowindex`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowindex) on each cell. The [`aria-colindex`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colindex) or [`aria-rowindex`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowindex) is set to the position of a cell within the row or column, respectively. If the table includes cells that span multiple rows or multiple columns, then [`aria-rowspan`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowspan) or [`aria-colspan`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colspan) should be included as well. Realize, it is much simpler to use the {{HTMLElement('table')}} element, along with all the related semantic elements and attributes that are all supported by all assistive technologies. To create an interactive widget that has a tabular structure, use the `grid` pattern instead. If the interaction provides for the selection state of individual cells, if left to right and top to bottom navigation is provided, or if the user interface allows the rearranging of cell order or otherwise changing individual cell order such as through drag and drop, use [`grid`](/en-US/docs/Web/Accessibility/ARIA/Roles/grid_role) or [`treegrid`](/en-US/docs/Web/Accessibility/ARIA/Roles/treegrid_role) instead. > **Note:** Using a native HTML table element whenever possible is strongly encouraged. ### Associated WAI-ARIA roles, states, and properties - `role="rowgroup"` - : An optional child of the table, the row group encapsulates a group of rows, similar to {{HTMLElement('thead')}}, {{HTMLElement('tbody')}}, and {{HTMLElement('tfoot')}}. - [`role="row"`](/en-US/docs/Web/Accessibility/ARIA/Roles/row_role) - : A row within the table, and optionally within a rowgroup, that is a container for one or more cells, columnheaders, or rowheaders. - [`aria-describedby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby) attribute - : Takes as its value the id of the element that serves as a description for the table. - [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) attribute - : The [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) provides an accessible name for the table. - [`aria-colcount`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colcount) attribute - : This attribute is only required if the columns are not present in the DOM all the time. It provides an explicit indication of the number of columns in the full table. Set the value to the total number of columns in the full table. If unknown, set `aria-colcount="-1"`. - [`aria-rowcount`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowcount) attribute - : This attribute is only required if the rows are not present in the DOM all the time, such as scrollable tables that reuse rows to minimize the number of DOM nodes. It provides an explicit indication of the number of rows in the full table. Set the value to the total number of rows in the full table. If unknown, set `aria-rowcount="-1"`. ### Keyboard interactions None ### Required JavaScript features None. For sortable columns, see the [columnheader](/en-US/docs/Web/Accessibility/ARIA/Roles/columnheader_role) aria role. > **Note:** The first rule of ARIA use is if you can use a native feature with the semantics and behavior you require already built in, instead of re-purposing an element and **adding** an ARIA role, state or property to make it accessible, then do so. Employ the HTML {{HTMLElement('table')}} element instead of the ARIA role of table whenever possible. ## Examples ```html <div role="table" aria-label="Semantic Elements" aria-describedby="semantic_elements_table_desc" aria-rowcount="81"> <div id="semantic_elements_table_desc"> Semantic Elements to use instead of ARIA's roles </div> <div role="rowgroup"> <div role="row"> <span role="columnheader" aria-sort="none">ARIA Role</span> <span role="columnheader" aria-sort="none">Semantic Element</span> </div> </div> <div role="rowgroup"> <div role="row" aria-rowindex="11"> <span role="cell">header</span> <span role="cell">h1</span> </div> <div role="row" aria-rowindex="16"> <span role="cell">header</span> <span role="cell">h6</span> </div> <div role="row" aria-rowindex="18"> <span role="cell">rowgroup</span> <span role="cell">thead</span> </div> <div role="row" aria-rowindex="24"> <span role="cell">term</span> <span role="cell">dt</span> </div> </div> </div> ``` The above is part of a table. While the full table has 81 entries, as indicated by the [`aria-rowcount`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowcount) property, only four are currently visible. The columns are sortable, but not currently sorted, as indicated by the [`aria-sort`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-sort) property on the column headers. ## Best practices Only use {{HTMLElement('table')}}, {{HTMLElement('tbody')}}, {{HTMLElement('thead')}}, {{HTMLElement('tr')}}, {{HTMLElement('th')}}, {{HTMLElement('td')}}, etc., for data table structure. You can add these ARIA roles to ensure accessibility should the native semantics of the table be removed, such as with CSS. A relevant use case for the ARIA table role is when CSS's display property overrides the native semantics of a table, such as by `display: grid`. In this case, you can use the ARIA table roles to re-add the semantics. ### Added benefits none ## Specifications {{Specifications}} ## See also - [HTML table element](/en-US/docs/Learn/HTML/Tables/Advanced) - [HTML table tutorial](/en-US/docs/Learn/HTML/Tables/Basics) - [ARIA: `grid` role](/en-US/docs/Web/Accessibility/ARIA/Roles/grid_role) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/complementary_role/index.md
--- title: "ARIA: complementary role" slug: Web/Accessibility/ARIA/Roles/complementary_role page-type: aria-role spec-urls: - https://w3c.github.io/aria/#complementary - https://www.w3.org/WAI/ARIA/apg/patterns/landmarks/examples/complementary.html --- The `complementary` [landmark role](/en-US/docs/Web/Accessibility/ARIA/Roles#3._landmark_roles) is used to designate a supporting section that relates to the main content, yet can stand alone when separated. These sections are frequently presented as sidebars or call-out boxes. If possible, use the [HTML \<aside> element](/en-US/docs/Web/HTML/Element/aside) instead. ```html <div role="complementary"> <h2>Our partners</h2> <!-- complementary section content --> </div> ``` This is a sidebar containing links to project sponsors. ## Description The `complementary` role is [a landmark](/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques#landmark_roles) role. Landmarks can be used by assistive technology to quickly identify and navigate to large sections of the document. Content listed within a container with the `complementary` landmark role should make sense if separated from the main content of the document. > **Note:** Using the {{HTMLElement('aside')}} element will automatically communicate a section has a role of `complementary`. Developers should always prefer using the correct semantic HTML element over using ARIA. ## Examples ```html <div role="complementary"> <h2>Trending articles</h2> <ul> <li><a href="#">18 tweets that will make you feel all the feels</a></li> <li> <a href="#">Stop searching! I've found the perfect lunch containers.</a> </li> <li> <a href="#">The time has come to decide how to call these foods</a> </li> <li><a href="#">17 really good posts we saw on Tumblr this week</a></li> <li><a href="#">10 parent hacks we know work because we tried them</a></li> </ul> </div> ``` ## Accessibility concerns [Landmark roles](/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques#landmark_roles) are intended to be used sparingly, to identify larger overall sections of the document. Using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page. ## Best practices ### Prefer HTML Using the {{HTMLElement('aside')}} element will automatically communicate a section has a role of `complementary`. If at all possible, prefer using it instead. ### Labeling landmarks #### Multiple landmarks If there is more than one `complementary` landmark role or {{HTMLElement('aside')}} element in a document, provide a label for each landmark using the [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) attribute, or, if the aside has an appropriately descriptive title, point to it with the [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) attribute. This label will allow an assistive technology user to be able to quickly understand the purpose of each landmark. ```html <aside aria-label="Note about usage"> <!-- content --> </aside> … <aside id="sidebar" aria-label="Sponsors"> <!-- content --> </aside> ``` #### Redundant descriptions Screen readers will announce the type of role the landmark is. Because of this, you do not need to describe what the landmark is in its label. For example, a declaration of `role="complementary"` with an of `aria-label="Sidebar"` may be announced redundantly as, "complementary sidebar". ### Added benefits Certain technologies such as browser extensions can generate lists of all landmark roles present on a page, allowing non-screen reader users to also quickly identify and navigate to large sections of the document. - [Landmarks browser extension](https://matatk.agrip.org.uk/landmarks/) ## Specifications {{Specifications}} ## See also - [\<aside>: The Aside element](/en-US/docs/Web/HTML/Element/aside) - [complementary (role): Accessible Rich Internet Applications (WAI-ARIA) 1.1](https://www.w3.org/TR/wai-aria/#complementary) - [Using HTML sections and outlines](/en-US/docs/Web/HTML/Element/Heading_Elements) - [Landmark roles: Using ARIA: Roles, States, and Properties](/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques#landmark_roles) - [Using WAI-ARIA Landmarks – 2013 | The Paciello Group](https://www.tpgi.com/using-wai-aria-landmarks-2013/) - [Accessible Landmarks | scottohara.me](https://www.scottohara.me/blog/2018/03/03/landmarks.html) - [Aside Revisited | HTML5 Doctor](https://html5doctor.com/aside-revisited/) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/menuitemradio_role/index.md
--- title: "ARIA: menuitemradio role" slug: Web/Accessibility/ARIA/Roles/menuitemradio_role page-type: aria-role spec-urls: - https://w3c.github.io/aria/#menuitemradio - https://www.w3.org/WAI/ARIA/apg/patterns/menubar/examples/menubar-navigation/ --- A `menuitemradio` is checkable menuitem in a set of elements with the same role, only one of which can be checked at a time. ## Description The items in menu and menubars are menu items. There are three types of menu items: [`menuitem`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitem_role), [`menuitemcheckbox`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemcheckbox_role), and `menuitemradio`. To limit the number of checked menu items to one within a group, use the `menuitemradio` role on all the elements in the group. A `menuitemradio` is checkable menuitem in a set of elements with the same role, of which only can be checked at a time. The three menu item elements can only be contained in, or owned by, an element with role [`menu`](/en-US/docs/Web/Accessibility/ARIA/Roles/menu_role) or [`menubar`](/en-US/docs/Web/Accessibility/ARIA/Roles/menubar_role), optionally nested within a grouping element with role of [`group`](/en-US/docs/Web/Accessibility/ARIA/Roles/group_role). Being nested or otherwise owned (see [`aria-owns`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-owns)) in a `menu` or `menubar` identifies the menu items as being related widgets. When all items in a submenu are members of the same radio group, the `group` is defined by the menu element; the `group` element is not necessary. Menu items containing the role of `menuitemradio` must include the [`aria-checked`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked) attribute to expose the radio button's state to assistive technology, unless using [`<input type="radio">`](/en-US/docs/Web/HTML/Element/input/checkbox), in which case the ['checked'](/en-US/docs/Web/HTML/Element/input/checkbox#checked) attribute should be used. Similar to the 'checked' attribute of {{HTMLElement('input')}}s of type `radio`, the `aria-checked` attribute of a `menuitemradio` indicates whether the menu item is checked (`true`), unchecked (`false`). If missing, the value defaults to `false`. There is no `mixed` value like there is for `menuitemcheckbox`. Only one `menuitemradio` in a group can be checked at the same time. When one item in the group is checked, the `aria-checked` attribute gets set to `true`, while the previously checked `menuitemradio` element in the same group, if there was one, becomes unchecked, by having the `aria-checked` attribute value switched to `false`. If your want more than one item in a group to be checked, or if you want to enable checking and unchecking an item, consider using `menuitemcheckbox`. If a `menu` or `menubar` contains more than one group of `menuitemradio` elements, or if the `menu` contains a group of `menuitemradio` elements as well as other, unrelated `menuitem` elements and/or `menuitemcheckbox` elements, contain each set of related `menuitemradio` elements in a `group` element or delimit the group the `menuitemradio` elements from the other menu items with a `separator` element (or an HTML element with an equivalent role such as a {{HTMLElement('fieldset')}} grouping or a thematic break {{HTMLElement('hr')}} separator. An accessible name is required. Ideally, the accessible name should come from an associated {{htmlelement('label')}} element if using `<input type="radio">` or visible, descendant content. Realize if the label or descendant content is not sufficient and, preferably, [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) is used referencing non-descendant content or [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) is used, these two ARIA properties will hide other descendant content from assistive technologies. If all elements in the set are not present in the DOM include the [`aria-setsize`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-setsize) and [`aria-posinset`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-posinset) properties. When specifying `aria-setsize` and `aria-posinset` on a `menuitemradio`, set the value with respect to the total number of items in the menu, excluding any separators. The `menuitemradio` element can have phrasing content, but can not have interactive content as descendants and no descendants with a `tabindex` attribute specified. ### All descendants are presentational There are some types of user interface components that, when represented in a platform accessibility API, can only contain text. Accessibility APIs do not have a way of representing semantic elements contained in a `menuitemradio`. To deal with this limitation, browsers, automatically apply role [`presentation`](/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role) to all descendant elements of any `menuitemradio` element as it is a role that does not support semantic children. For example, consider the following `menuitemradio` element, which contains a heading. ```html <div role="menuitemradio"><h6>Name of my radio button</h6></li> ``` Because descendants of `menuitemradio` are presentational, the following code is equivalent: ```html <div role="menuitemradio"><h6 role="presentation">Name of my radio button</h6></li> ``` From the assistive technology user's perspective, the heading does not exist since the previous code snippets are equivalent to the following in the [accessibility tree](/en-US/docs/Glossary/Accessibility_tree): ```html <div role="menuitemradio">Name of my radio button</div> ``` ### Associated WAI-ARIA roles, states, and properties - [`menu`](/en-US/docs/Web/Accessibility/ARIA/Roles/menu_role) role - : Widget that offers a list of common actions or functions the user can invoke. - [`menubar`](/en-US/docs/Web/Accessibility/ARIA/Roles/menubar_role) role - : Similar to `menu` for a consistent set of frequently used commands remaining visible and usually presented horizontally. - [`group`](/en-US/docs/Web/Accessibility/ARIA/Roles/group_role) role - : Container for a group of `menuitem` elements, including `menuitemradio` elements within a `menu` or `menubar`. - [`aria-checked`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked) (Required) - : Set to `true`, `false`, or `mixed`, it indicates the current "checked" state of the menuitemradio ### Keyboard interactions When a `menu` opens, or when a `menubar` receives focus, keyboard focus is placed on the first item. All items in both are focusable, including all `menuitemradio` elements. If the `menuitemradio` is in a submenu in a `menubar` or a menu opened with a menu button, the following keyboard interactions must be programmed in. : - <kbd>Enter</kbd> - : If not checked, checks the focused `menuitemradio` and unchecks any other checked `menuitemradio` element in the same group. Also, closes the menu. - <kbd>Space</kbd> - : If not checked, checks the focused `menuitemradio` and unchecks any other checked `menuitemradio` element in the same group without closing the menu. - <kbd>Escape</kbd> - : Closes menu. In menubar, moves focus to parent menubar item. - <kbd>Right Arrow</kbd> - : Closes submenu. In menubar, moves focus to next item in the menubar, opening any submenu if there is one. - <kbd>Left Arrow</kbd> - : Closes menu. In menubar, moves focus to previous item in the menubar, opening any submenu if there is one. - <kbd>Down Arrow</kbd> - : Moves focus to the next item in the menu. If focus is on the last item, moves focus to the first item. - <kbd>Up Arrow</kbd> - : Moves focus to previous item in the menu. If focus is on the first item, moves focus to the last item. - <kbd>Home</kbd> - : Moves focus to the first item in the menu. - <kbd>End</kbd> - : Moves focus to the last item in the menu. - <kbd>Character</kbd> - : Moves focus to the next item having a name that starts with the typed character. If none of the items have a name starting with the typed character, focus does not move. ### Required JavaScript #### Required event handlers - `onclick` - : Handle mouse clicks on both the radio button and the associated label that will change the state of the radio button by changing the value of the `aria-checked` attribute and the appearance of the radio button so it appears checked or unchecked to the sighted user - `onKeyDown` - : Handle the case where the user presses the <kbd>Space</kbd> key to change the state of the radio button by changing the value of the `aria-checked` attribute and the appearance of the radio button so it appears checked or unchecked to the sighted user. Also handles all keys listed in the keyboard navigation section above. ## Examples ```html <li role="menuitemradio" tabindex="-1" aria-checked="false">Purple</li> ``` The [`tabindex="-1"`](/en-US/docs/Web/HTML/Global_attributes/tabindex) makes the `menuitemradio` focusable but not part of the page tab sequence. Had we included `aria-checked="true"` it would have indicated that the `menuitemradio` was checked, and we would have visually styled the selected state to look checked using the attribute selector `[role='menuitemradio'][aria-checked='true']`. Instead, the presence of `aria-checked="false"` indicates to assistive technologies that the `menuitemradio` is checkable but not currently checked. The accessible name "purple" comes from the contents. The visual appearance of the selected state is a checked radio button which we can create using [generated content](/en-US/docs/Web/CSS/CSS_generated_content), making it visible and the same color as the content by synchronizing with the `aria-checked` value using CSS [attribute selectors](/en-US/docs/Web/CSS/Attribute_selectors) and changing the [`background-color`](/en-US/docs/Web/CSS/background-color). ```css [role="menuitemradio"]::before { display: inline-block; content: ""; width: 1em; height: 1em; padding: 0.1em; border: 2px solid #333; border-radius: 50%; box-sizing: border-box; background-clip: content-box; margin-inline-end: 2px; } [role="menuitemradio"][aria-checked="true"]::before { background-color: purple; } ``` Don't use the [`background`](/en-US/docs/Web/CSS/background) shorthand property, as that will override the [`background-clip`](/en-US/docs/Web/CSS/background-clip) property we used to create the radio button effect. ### Prefer HTML The first rule of ARIA is: if a native HTML element or attribute has the semantics and behavior you require, use it instead of re-purposing an element and adding an ARIA role, state or property to make it accessible. As such, it is recommended to use the native [HTML radio button](/en-US/docs/Web/HTML/Element/input/radio) form control instead of recreating a radio button's functionality with JavaScript and ARIA. ## Specifications {{Specifications}} ## See also - [`radio` role](/en-US/docs/Web/Accessibility/ARIA/Roles/radio_role) - [`<input type="radio">`](/en-US/docs/Web/HTML/Element/input/radio) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria/roles
data/mdn-content/files/en-us/web/accessibility/aria/roles/menuitem_role/index.md
--- title: "ARIA: menuitem role" slug: Web/Accessibility/ARIA/Roles/menuitem_role page-type: aria-role spec-urls: - https://w3c.github.io/aria/#menuitem - https://www.w3.org/WAI/ARIA/apg/patterns/menubar/examples/menubar-navigation/ --- The `menuitem` role indicates the element is an option in a set of choices contained by a `menu` or `menubar`. ## Description A `menuitem` is one of the three types of options in a set of choices contained by a [`menu`](/en-US/docs/Web/Accessibility/ARIA/Roles/menu_role) or [`menubar`](/en-US/docs/Web/Accessibility/ARIA/Roles/menubar_role); the other two being [`menuitemcheckbox`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemcheckbox_role) and [`menuitemradio`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemradio_role). The `menuitem` is only found as a descendant of, or owned by, elements with role `menu` or `menubar`, optionally nested within an element with role [`group`](/en-US/docs/Web/Accessibility/ARIA/Roles/group_role) that is contained in, or owned by, a menu. If the `menuitem` is not a descendant of a menu in the DOM, include the [`aria-owns`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-owns) attribute on menu to indicate the relationship. If `aria-owns` is set on the menu container to include elements that are not DOM children of the container, those elements will appear in the reading order in the sequence they are referenced and after any items that are DOM children in supporting technologies. Ensure the visual focus order matches the assistive technology reading order. Every `menuitem` in a menu is focusable, whether or not it is disabled. Indicate a `menuitem` is disabled by setting [`aria-disabled="true"`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-disabled) on the element with the role. If a `menuitem` has a submenu, program it to display a new sub-level menu when the menu item is activated and include [`aria-haspopup="menu"`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-haspopup) or with the `true` value to indicate to assistive technologies that the menu item is used to open a submenu. A common convention for indicating that a `menuitem` launches a dialog box is to append "…" (ellipsis) to the menu item label, e.g., "Save as …". Every `menuitem` must have an accessible name. This name comes from the element's contents by default. If the contents don't provide for a useful accessible name, [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) can be used to reference visible label. If no visible content is available to provide the accessible name, an accessible name can be provided with [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label). ## Associated WAI-ARIA roles, states, and properties - [`menu`](/en-US/docs/Web/Accessibility/ARIA/Roles/menu_role) role - : A widget providing a list of choices. Required context role (or `menubar`) - [`menubar`](/en-US/docs/Web/Accessibility/ARIA/Roles/menubar_role) role - : A presentation of a `menu` that usually remains visible and is usually presented horizontally. Required context role (or `menu`) - [`group`](/en-US/docs/Web/Accessibility/ARIA/Roles/group_role) role - : Can be used to identify a set of related `menuitem`s within or otherwise owned by a `menu` or `menubar` - [`aria-disabled`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-disabled) - : Indicates the element is perceivable but disabled, so it is not operable - [`aria-haspopup`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-haspopup) - : Indicates the availability and type of interactive popup that can be triggered by the `menuitem` ## Keyboard interactions - <kbd>Enter</kbd> and <kbd>Space</kbd> - : If the `menuitem` has a submenu, opens the submenu and places focus on its first item. Otherwise, activates the item and closes the menu. - <kbd>Down Arrow</kbd> - : On a `menuitem` that has a submenu in a `menubar`, opens the submenu and places focus on the first item in the submenu. Otherwise, moves focus to the next item, optionally wrapping from the last to the first. - <kbd>Up Arrow</kbd> - : Moves focus to the previous item, optionally wrapping from the first to the last. Optionally, if the `menuitem` is in a menubar and has a submenu, opens the submenu and places focus on the last item in the submenu. - <kbd>Right Arrow</kbd> - : If in a `menu` opened with a menubutton and not in a `menubar`, if the menuitem does not have a submenu, does nothing. When focus is in a `menubar`, moves focus to the next item, optionally wrapping from the last to the first. When focus is in a `menu` and on a `menuitem` that has a submenu, opens the submenu and places focus on its first item. When focus is in a `menu` and on an item that does not have a submenu, closes the submenu and any parent menus, moves focus to the next item in the `menubar`, and, if focus is now on a `menuitem` with a submenu, either opens the submenu of that `menuitem` without moving focus into the submenu, or opens the submenu of that `menuitem` and places focus on the first item in the submenu. - <kbd>Left Arrow</kbd> - : When focus is in a `menubar`, moves focus to the previous item, optionally wrapping from the first to the last. When focus is in a submenu of an item in a menu, closes the submenu and returns focus to the parent `menuitem`. When focus is in a submenu of an item in a `menubar`, closes the submenu, moves focus to the previous item in the `menubar`, and, if focus is now on a `menuitem` with a submenu, either opens the submenu of that `menuitem` without moving focus into the submenu, or opens the submenu of that `menuitem` and places focus on the first item in the submenu. - <kbd>Home</kbd> - : If arrow key wrapping is not supported, moves focus to the first item in the current `menu` or `menubar`. - <kbd>End</kbd> - : If arrow key wrapping is not supported, moves focus to the last item in the current `menu` or `menubar`. - Any key that corresponds to a printable character (Optional) - : Move focus to the next item in the current menu whose label begins with that printable character. - <kbd>Escape</kbd> - : Close the menu that contains focus and return focus to the element or context, e.g., menu button or parent `menuitem`, from which the menu was opened. - <kbd>Tab</kbd> - : Moves focus to the next element in the tab sequence, and if the item that had focus is not in a menubar, closes its menu and all open parent menu containers. - <kbd>Shift + Tab</kbd> - : Moves focus to the previous element in the tab sequence, and if the item that had focus is not in a menubar, closes its menu and all open parent menu containers. If a menu is opened or a menu bar receives focus as a result of a context action, <kbd>Escape</kbd> or <kbd>Enter</kbd> may return focus to the invoking context. Some implementations of navigation menubars may have menuitem elements that both perform a function and open a submenu. In such implementations, <kbd>Enter</kbd> and <kbd>Space</kbd> perform a navigation function while <kbd>Down Arrow</kbd>, in a horizontal menubar, opens the submenu associated with that same menuitem. When items in a `menubar` are arranged vertically and items in menu containers are arranged horizontally the <kbd>Down Arrow</kbd> performs as <kbd>Right Arrow</kbd> is described above, the <kbd>Up Arrow</kbd> performs as <kbd>Left Arrow</kbd> is described above, and vice versa. ## Examples ```html <div> <button id="menubutton" aria-haspopup="true" aria-controls="menu"> <img src="hamburger.svg" alt="Page Sections" /> </button> <ul id="menu" role="menu" aria-labelledby="menubutton"> <li role="presentation"> <a role="menuitem" href="#description">Description</a> </li> <li role="presentation"> <a role="menuitem" href="#associated_wai-aria_roles_states_and_properties"> Associated WAI-ARIA roles, states, and properties </a> </li> <li role="presentation"> <a role="menuitem" href="#keyboard_interactions"> Keyboard interactions </a> </li> <li role="presentation"> <a role="menuitem" href="#examples">Examples</a> </li> <li role="presentation"> <a role="menuitem" href="#specifications">Specifications</a> </li> <li role="presentation"> <a role="menuitem" href="#see_also">See Also</a> </li> </ul> </div> ``` ## Specifications {{Specifications}} ## See also - [`menuitemcheckbox` role](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemcheckbox_role) - [`menuitemradio` role](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemradio_role) - [`listitem` role](/en-US/docs/Web/Accessibility/ARIA/Roles/listitem_role) - [`option` role](/en-US/docs/Web/Accessibility/ARIA/Roles/option_role) <section id="Quick_links"> 1. [**WAI-ARIA roles**](/en-US/docs/Web/Accessibility/ARIA/Roles) {{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Roles", 1)}} </section>
0
data/mdn-content/files/en-us/web/accessibility/aria
data/mdn-content/files/en-us/web/accessibility/aria/annotations/index.md
--- title: ARIA annotations slug: Web/Accessibility/ARIA/Annotations page-type: guide --- <section id="Quick_links"> <ol> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Annotations">ARIA annotations</a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Guides">ARIA guides</a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions">ARIA live regions</a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Screen_Reader_Implementors_Guide">ARIA screen reader implementors guide</a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques">Using ARIA: Roles, states, and properties</a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Multipart_labels">Multipart labels</a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/How_to_file_ARIA-related_bugs">How to file ARIA-related bugs</a></li> <li class="toggle"> <details><summary>ARIA states and properties</summary> {{ListSubpagesForSidebar("Web/Accessibility/ARIA/Attributes", 1)}} </details> </li> <li class="toggle"> <details><summary>WAI-ARIA Roles</summary> {{ListSubpagesForSidebar("Web/Accessibility/ARIA/Roles", 1)}} </details> </li> </ol> </section> WAI-ARIA version 1.3 sees the addition of a set of new features, collectively known as ARIA annotations, which allow the creation of accessible annotations inside web documents. Typical use cases include edit suggestions (i.e. an addition and/or deletion in an editable document), and comments (e.g. an editorial comment related to a part of a document under review). Below we'll introduce the new features associated with ARIA annotations, and have a look at some code examples that show them in action. > **Note:** You can find all the examples discussed in this article in a demo file at [aria-annotations](https://mdn.github.io/html-examples/aria-annotations/). ## ARIA annotations features The ARIA attributes providing these new abilities are as follows: - `aria-description=""` — provides a detailed description of an HTML element, as opposed to the brief label provided by [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label). - `role="insertion"` and `role="deletion"` — semantically denote HTML elements whose contents represent an insertion to or deletion from the overall document. These are semantically equivalent to the HTML {{HTMLElement('ins')}} and {{HTMLElement('del')}} elements. Note that these aren't part of the new ARIA annotations features, but they are of central relevance. - `role="mark"` — semantically denotes HTML elements containing text that is marked/highlighted for reference purposes. This is semantically equivalent to the HTML {{HTMLElement('mark')}} element. - `role="suggestion"` — semantically denotes a single proposed change to an editable document. This should be used on an element that wraps a single insertion and deletion (see `role="insertion"` and `role="deletion"` above). - `role="comment"` — semantically denotes a comment/reaction to some content on the page, or to a previous comment. To provide a semantic association between the document content being annotated and the annotation, an `aria-details` attribute can be set on the annotated content that contains the ID of the annotated element. `aria-details` has been updated so that it can support multiple IDs — this makes sense, for example you can easily envisage having multiple comments relating to the same bit of text. ARIA annotation roles and objects are currently exposed in: - Firefox from version 75 onwards, on Windows and Linux (on macOS, we are first waiting for Apple to define what Safari will expose as Apple-dialect attributes to VoiceOver, and will then follow suit.) - Chrome from version 81 onwards, currently behind the `#enable-accessibility-expose-aria-annotations` flag (go to `chrome://flags` to enable this.) Unfortunately, you won't be able to use any of these yet, as screen reader support is currently not there. For the moment, you can see the annotations data being exposed with tools like [Firefox Accessibility Inspector](https://firefox-source-docs.mozilla.org/devtools-user/accessibility_inspector/index.html). The annotations should just work once screen reader support is added. ## Associating annotated elements with their details There are a number of different ways in which you can associate UI features with text labels or descriptions for accessibility purposes. It is useful to know when to use each. You'll see examples of most of these later on in the article, but briefly: - `aria-label=""` can be set on an element to provide a brief descriptive label when it isn't appropriate to have the label actually appearing in the UI, for example a [search input](/en-US/docs/Web/HTML/Element/input/search) in a horizontal nav bar. - `aria-labelledby=""` can be set on an element and given a value the same as the ID of an element that contains a label for the element. This is useful when the element's label is available in the UI, but for some reason a conventional {{HTMLElement('label')}} won't work. - `aria-description=""` is similar to `aria-label=""` in that it accepts a string of text, but is used when you want to give an element a description, in addition to its short label. - `aria-describedby=""` is analogous to `aria-labelledby=""` in that it accepts an ID reference, but is used when you want to associate the element with a more detailed description, in addition to its short label. - `aria-details=""` references a more complex sets of details, distinct from simple text descriptions. You can learn more about this in the next section. ### aria-details versus aria-describedby We have already alluded to the difference between these two above — `aria-describedby` is for textual descriptions, whereas `aria-details` is for more complex sets of details. But what does this actually mean? `aria-describedby` is appropriate for associating an element with a simple text description, where you don't have much in the way of meaningful semantics contained within. For example: ```html <p id="description-id">An extended text description of some kind.</p> <div aria-describedby="description-id"> <!-- Some kind of UI feature that needs an {{glossary("accessible description")}} --> </div> ``` `aria-details` is appropriate when linking to descriptions or annotations that are a bit more complex — rather than a simple text string, it might contain multiple bits of semantic information: ```html <div id="detail-id"> <h2>A heading</h2> <p>An extended text description of some kind…</p> <p><time datetime="…">A timestamp</time></p> </div> <div aria-details="detail-id"> <!-- Some kind of UI feature where additional details might be useful --> </div> ``` This difference becomes apparent when you get to how the content is interpreted in the accessibility layer and presented by screen readers, both in interaction guidance and through the [accessible name and description computation](https://www.w3.org/TR/accname/). Content associated via `aria-describedby` becomes part of the accessible description and is flattened into a simple string (lists, links, etc. are not exposed). Generally it is announced after the accessible name. ARIA 1.3 also identifies [which roles _disallow_ its use](https://w3c.github.io/aria/#namefromprohibited) (such as `generic`, which maps to `<div>`). Content associated via `aria-details` is _not_ factored into the {{glossary("accessible description")}} computation. A screen reader would ideally make the user aware the content is available and then let the user navigate directly to that content. As such, it can contain rich content. The role of the referenced element (eg: `comment`, `definition`) may affect how a screen reader exposes or references the content. `aria-details` has no restrictions on which roles may use it. ## A basic description Simple descriptions basically just involve usage of `aria-description` on an element to provide a description that can't be gotten from the element's text alone. As an example, let's say you have a poll/voting UI widget that shows numbers of votes, but you want to summarize the purpose of the widget in a clear description because the UI does not make it clear: ```html <section aria-description="Choose your favorite fruit — the fruit with the highest number of votes will be added to the lunch options next week."> <form> <fieldset> <legend> <p>Pick your favorite fruit:</p> </legend> <ul> <li> <label >Apple: <input type="radio" name="fruit" value="apple" /></label> </li> <li> <label >Orange: <input type="radio" name="fruit" value="orange" /></label> </li> <li> <label >Banana: <input type="radio" name="fruit" value="banana" /></label> </li> </ul> </fieldset> </form> </section> ``` If the descriptive text does appear in the UI (it should for this example), you can link the description to the widget using `aria-describedby`, like so: ```html <p id="fruit-desc"> Choose your favorite fruit — the fruit with the highest number of votes will be added to the lunch options next week. </p> <section aria-describedby="fruit-desc"> <form> <fieldset> <legend> <p>Pick your favorite fruit:</p> </legend> <ul> <li> <label >Apple: <input type="radio" name="fruit" value="apple" /></label> </li> <li> <label >Orange: <input type="radio" name="fruit" value="orange" /></label> </li> <li> <label >Banana: <input type="radio" name="fruit" value="banana" /></label> </li> </ul> </fieldset> </form> </section> ``` ## Insertions and deletions A common wish in online document systems like Google Docs is to be able to track changes, to see what reviewers or editors have suggested as changes to the text, before the managing editor or author accepts or rejects those changes. The semantics for this have long been available in HTML, via the {{HTMLElement('ins')}} and {{HTMLElement('del')}} elements: ```html <p> Freida's pet is a <del>black Cat called Luna</del ><ins>purple Tyrannosaurus Rex called Tiny</ins>. </p> ``` With the new additions, you now have new roles available to provide the same semantics, should you be unable to use {{HTMLElement('ins')}} and {{HTMLElement('del')}} elements for some reason: ```html <p> Freida's pet is a <span role="deletion">black Cat called Luna</span ><span role="insertion">purple Tyrannosaurus Rex called Tiny</span>. </p> ``` However, this often isn't enough — when you've got a content change like the one above that involves an insertion _and_ a deletion, there is no way for a screen reader user to work out if the two are related or not. This is the job of `role="suggestion"`, which should be set on an element wrapping both of them like so: ```html <p> Freida's pet is a <span role="suggestion" ><span role="deletion">black Cat called Luna</span ><span role="insertion">purple Tyrannosaurus Rex called Tiny</span></span >. </p> ``` We could even provide an information box saying who made the suggestion and when, and associate it with the suggestion via `aria-details`: ```html <p> Freida's pet is a <span role="suggestion" aria-details="comment-source"> <span role="deletion">black Cat called Luna</span> <span role="insertion">purple Tyrannosaurus Rex called Tiny</span></span >. </p> <div id="comment-source"> Suggested by Chris, <time datetime="2019-03-30T19:29">March 30 2021, 19:29</time> </div> ``` Browsers tend to provide a default black strikethrough for deletions, and a black underline for insertions, but you'll probably want to use some more interesting styling of your own, for example: ```css ins, [role="insertion"] { color: #0c0; text-decoration: underline; } del, [role="deletion"] { color: red; text-decoration: line-through; } ins, [role="insertion"], del, [role="deletion"] { text-decoration-thickness: 2px; background-color: #fee; padding: 2px 4px; margin: 0 1px; } ``` ## Comments Online document applications also commonly feature commenting systems, and it would be nice to have a way to semantically associate commented content and its comments. ARIA annotations can help us here too. Let's say we have a comment box like so: ```html <div role="comment" id="thread-1" data-author="chris"> <h3>Chris said</h3> <p class="comment-text">I really think this could use more cowbell.</p> <p><time datetime="2019-03-30T19:29">March 30 2019, 19:29</time></p> </div> ``` We've used `role="comment"` to mark this up as a comment. To associate the comment with the text being commented, we need to wrap the commented text with an element containing the `aria-details` attribute, the value of which should be the ID of the comment. {{HTMLElement('mark')}} is a suitable element for this purpose (a comment is a reference annotation), so the annotation could look like this: ```html <p> The last half of the song is a slow-rising crescendo that peaks at the <mark aria-details="thread-1">end of the guitar solo</mark>, before fading away sharply. </p> <div role="comment" id="thread-1" data-author="chris"> <h3>Chris said</h3> <p class="comment-text">I really think this moment could use more cowbell.</p> <p><time datetime="2019-03-30T19:29">March 30 2019, 19:29</time></p> </div> ``` > **Note:** If for some reason you can't use the {{HTMLElement('mark')}} element in your application, you could also use [`<span role="mark"></span>`](/en-US/docs/Web/Accessibility/ARIA/Roles/mark_role). Since `aria-details` can now accept multiple IDs, we can associate multiple comments with the same annotation, like so: ```html <p> The last half of the song is a slow-rising crescendo that peaks at the <mark aria-details="thread-1 thread-2">end of the guitar solo</mark>, before fading away sharply. </p> <div role="comment" id="thread-1" data-author="chris"> <h3>Chris said</h3> <p class="comment-text">I really think this moment could use more cowbell.</p> <p><time datetime="2019-03-30T19:29">March 30 2019, 19:29</time></p> </div> <div role="comment" id="thread-2" data-author="chris"> <h3>Marcus said</h3> <p class="comment-text"> The guitar solo could do with a touch more chorus, and a slightly lower volume. </p> <p><time datetime="2019-03-29T15:35">March 29 2019, 15:35</time></p> </div> ``` Nested comments are also possible with ARIA annotations — nest the comments inside one another, like so: ```html <div role="comment" id="thread-1" data-author="chris"> <h3>Chris said</h3> <p class="comment-text">I really think this moment could use more cowbell.</p> <p><time datetime="2019-03-30T19:29">March 30 2019, 19:29</time></p> <div role="comment" data-author="marcus"> <h3>Marcus replied</h3> <p class="comment-text"> I don't know about that. I think the cowbell could distract from the solo. </p> <p><time datetime="2019-03-30T21:02">March 30 2019, 21:02</time></p> </div> </div> ```
0
data/mdn-content/files/en-us/web/accessibility/aria
data/mdn-content/files/en-us/web/accessibility/aria/aria_techniques/index.md
--- title: "Using ARIA: Roles, states, and properties" slug: Web/Accessibility/ARIA/ARIA_Techniques page-type: guide --- <section id="Quick_links"> <ol> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Annotations">ARIA annotations</a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Guides">ARIA guides</a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions">ARIA live regions</a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Screen_Reader_Implementors_Guide">ARIA screen reader implementors guide</a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques">Using ARIA: Roles, states, and properties</a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Multipart_labels">Multipart labels</a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/How_to_file_ARIA-related_bugs">How to file ARIA-related bugs</a></li> <li class="toggle"> <details><summary>ARIA states and properties</summary> {{ListSubpagesForSidebar("Web/Accessibility/ARIA/Attributes", 1)}} </details> </li> <li class="toggle"> <details><summary>WAI-ARIA Roles</summary> {{ListSubpagesForSidebar("Web/Accessibility/ARIA/Roles", 1)}} </details> </li> </ol> </section> ARIA defines semantics that can be applied to elements, with these divided into **roles** (defining a type of user interface element) and **states** and **properties** that are supported by a role. Authors must assign an ARIA role and the appropriate states and properties to an element during its life-cycle, unless the element already has appropriate ARIA semantics (via use of an appropriate HTML element). Addition of ARIA semantics only exposes extra information to a browser's accessibility API, and does not affect a page's DOM. ## Roles ### Widget roles - [`button`](/en-US/docs/Web/Accessibility/ARIA/Roles/button_role) - [`checkbox`](/en-US/docs/Web/Accessibility/ARIA/Roles/checkbox_role) - [`gridcell`](/en-US/docs/Web/Accessibility/ARIA/Roles/gridcell_role) - [`link`](/en-US/docs/Web/Accessibility/ARIA/Roles/link_role) - [`menuitem`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitem_role) - [`menuitemcheckbox`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemcheckbox_role) - [`menuitemradio`](/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemradio_role) - [`option`](/en-US/docs/Web/Accessibility/ARIA/Roles/option_role) - [`progressbar`](/en-US/docs/Web/Accessibility/ARIA/Roles/progressbar_role) - [`radio`](/en-US/docs/Web/Accessibility/ARIA/Roles/radio_role) - [`scrollbar`](/en-US/docs/Web/Accessibility/ARIA/Roles/scrollbar_role) - [`searchbox`](/en-US/docs/Web/Accessibility/ARIA/Roles/searchbox_role) - [`separator`](/en-US/docs/Web/Accessibility/ARIA/Roles/separator_role) (when focusable) - [`slider`](/en-US/docs/Web/Accessibility/ARIA/Roles/slider_role) - [`spinbutton`](/en-US/docs/Web/Accessibility/ARIA/Roles/spinbutton_role) - [`switch`](/en-US/docs/Web/Accessibility/ARIA/Roles/switch_role) - [`tab`](/en-US/docs/Web/Accessibility/ARIA/Roles/tab_role) - [`tabpanel`](/en-US/docs/Web/Accessibility/ARIA/Roles/tabpanel_role) - [`textbox`](/en-US/docs/Web/Accessibility/ARIA/Roles/textbox_role) - [`treeitem`](/en-US/docs/Web/Accessibility/ARIA/Roles/treeitem_role) ### Composite roles The techniques below describe each composite role as well as their required and optional child roles. - [`combobox`](/en-US/docs/Web/Accessibility/ARIA/Roles/combobox_role) - [`grid`](/en-US/docs/Web/Accessibility/ARIA/Roles/grid_role) (including [`row`](/en-US/docs/Web/Accessibility/ARIA/Roles/row_role), [`gridcell`](/en-US/docs/Web/Accessibility/ARIA/Roles/gridcell_role), [`rowheader`](/en-US/docs/Web/Accessibility/ARIA/Roles/rowheader_role), [`columnheader`](/en-US/docs/Web/Accessibility/ARIA/Roles/columnheader_role) roles) - [`listbox`](/en-US/docs/Web/Accessibility/ARIA/Roles/listbox_role) (including [`option`](/en-US/docs/Web/Accessibility/ARIA/Roles/option_role) role) - [`menu`](/en-US/docs/Web/Accessibility/ARIA/Roles/menu_role) - [`menubar`](/en-US/docs/Web/Accessibility/ARIA/Roles/menubar_role) - [`radiogroup`](/en-US/docs/Web/Accessibility/ARIA/Roles/radiogroup_role) (see [`radio role`](/en-US/docs/Web/Accessibility/ARIA/Roles/radio_role)) - [`tablist`](/en-US/docs/Web/Accessibility/ARIA/Roles/tablist_role) (including [`tab`](/en-US/docs/Web/Accessibility/ARIA/Roles/tab_role) and [`tabpanel`](/en-US/docs/Web/Accessibility/ARIA/Roles/tabpanel_role) roles) - [`tree`](/en-US/docs/Web/Accessibility/ARIA/Roles/tree_role) - [`treegrid`](/en-US/docs/Web/Accessibility/ARIA/Roles/treegrid_role) ### Document structure roles - [`application`](/en-US/docs/Web/Accessibility/ARIA/Roles/application_role) - [`article`](/en-US/docs/Web/Accessibility/ARIA/Roles/article_role) - [`cell`](/en-US/docs/Web/Accessibility/ARIA/Roles/cell_role) - [`columnheader`](/en-US/docs/Web/Accessibility/ARIA/Roles/columnheader_role) - [`definition`](/en-US/docs/Web/Accessibility/ARIA/Roles/definition_role) - [`directory`](/en-US/docs/Web/Accessibility/ARIA/Roles/directory_role) - [`document`](/en-US/docs/Web/Accessibility/ARIA/Roles/document_role) - [`feed`](/en-US/docs/Web/Accessibility/ARIA/Roles/feed_role) - [`figure`](/en-US/docs/Web/Accessibility/ARIA/Roles/figure_role) - [`group`](/en-US/docs/Web/Accessibility/ARIA/Roles/group_role) - [`heading`](/en-US/docs/Web/Accessibility/ARIA/Roles/heading_role) - [`img`](/en-US/docs/Web/Accessibility/ARIA/Roles/img_role) - [`list`](/en-US/docs/Web/Accessibility/ARIA/Roles/list_role) - [`listitem`](/en-US/docs/Web/Accessibility/ARIA/Roles/listitem_role) - [`math`](/en-US/docs/Web/Accessibility/ARIA/Roles/math_role) - [`none`](/en-US/docs/Web/Accessibility/ARIA/Roles/none_role) - [`note`](/en-US/docs/Web/Accessibility/ARIA/Roles/note_role) - [`presentation`](/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role) - [`row`](/en-US/docs/Web/Accessibility/ARIA/Roles/row_role) - [`rowgroup`](/en-US/docs/Web/Accessibility/ARIA/Roles/rowgroup_role) - [`rowheader`](/en-US/docs/Web/Accessibility/ARIA/Roles/rowheader_role) - [`separator`](/en-US/docs/Web/Accessibility/ARIA/Roles/separator_role) - [`table`](/en-US/docs/Web/Accessibility/ARIA/Roles/table_role) - [`term`](/en-US/docs/Web/Accessibility/ARIA/Roles/term_role) - [`toolbar`](/en-US/docs/Web/Accessibility/ARIA/Roles/toolbar_role) - [`tooltip`](/en-US/docs/Web/Accessibility/ARIA/Roles/tooltip_role) ### Landmark roles - [`banner`](/en-US/docs/Web/Accessibility/ARIA/Roles/banner_role) - [`complementary`](/en-US/docs/Web/Accessibility/ARIA/Roles/complementary_role) - [`contentinfo`](/en-US/docs/Web/Accessibility/ARIA/Roles/contentinfo_role) - [`form`](/en-US/docs/Web/Accessibility/ARIA/Roles/form_role) - [`main`](/en-US/docs/Web/Accessibility/ARIA/Roles/main_role) - [`navigation`](/en-US/docs/Web/Accessibility/ARIA/Roles/navigation_role) - [`region`](/en-US/docs/Web/Accessibility/ARIA/Roles/region_role) - [`search`](/en-US/docs/Web/Accessibility/ARIA/Roles/search_role) ### Live Region Roles - [`alert`](/en-US/docs/Web/Accessibility/ARIA/Roles/alert_role) - [`log`](/en-US/docs/Web/Accessibility/ARIA/Roles/log_role) - [`marquee`](/en-US/docs/Web/Accessibility/ARIA/Roles/marquee_role) - [`status`](/en-US/docs/Web/Accessibility/ARIA/Roles/status_role) - [`timer`](/en-US/docs/Web/Accessibility/ARIA/Roles/timer_role) ### Window Roles - [`alertdialog`](/en-US/docs/Web/Accessibility/ARIA/Roles/alertdialog_role) - [`dialog`](/en-US/docs/Web/Accessibility/ARIA/Roles/dialog_role) ## States and properties ### Widget attributes - [`aria-autocomplete`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-autocomplete) - [`aria-checked`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked) - [`aria-current`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-current) - [`aria-disabled`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-disabled) - [`aria-errormessage`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-errormessage) - [`aria-expanded`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-expanded) - [`aria-haspopup`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-haspopup) - [`aria-hidden`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-hidden) - [`aria-invalid`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-invalid) - [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) - [`aria-level`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-level) - [`aria-modal`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-modal) - [`aria-multiline`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-multiline) - [`aria-multiselectable`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-multiselectable) - [`aria-orientation`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-orientation) - [`aria-placeholder`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-placeholder) - [`aria-pressed`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-pressed) - [`aria-readonly`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-readonly) - [`aria-required`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-required) - [`aria-selected`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-selected) - [`aria-sort`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-sort) - [`aria-valuemax`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemax) - [`aria-valuemin`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemin) - [`aria-valuenow`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuenow) - [`aria-valuetext`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuetext) ### Live region attributes - [`aria-live`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-live) - [`aria-relevant`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-relevant) - [`aria-atomic`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-atomic) - [`aria-busy`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-busy) ### Drag &amp; drop attributes - [`aria-dropeffect`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-dropeffect) {{deprecated_inline}} - [`aria-grabbed`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-grabbed) {{deprecated_inline}} ### Relationship attributes - [`aria-activedescendant`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-activedescendant) - [`aria-colcount`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colcount) - [`aria-colindex`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colindex) - [`aria-colspan`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colspan) - [`aria-controls`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-controls) - [`aria-describedby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby) - [`aria-details`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-details) - [`aria-errormessage`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-errormessage) - [`aria-flowto`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-flowto) - [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) - [`aria-owns`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-owns) - [`aria-posinset`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-posinset) - [`aria-rowcount`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowcount) - [`aria-rowindex`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowindex) - [`aria-rowspan`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowspan) - [`aria-setsize`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-setsize) ### MicrosoftEdge-specific properties - [`x-ms-aria-flowfrom`](/en-US/docs/Web/Accessibility/ARIA) {{Non-standard_Inline}}
0
data/mdn-content/files/en-us/web/accessibility/aria
data/mdn-content/files/en-us/web/accessibility/aria/aria_live_regions/index.md
--- title: ARIA live regions slug: Web/Accessibility/ARIA/ARIA_Live_Regions page-type: guide --- <section id="Quick_links"> <ol> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Annotations">ARIA annotations</a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Guides">ARIA guides</a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions">ARIA live regions</a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Screen_Reader_Implementors_Guide">ARIA screen reader implementors guide</a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques">Using ARIA: Roles, states, and properties</a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Multipart_labels">Multipart labels</a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/How_to_file_ARIA-related_bugs">How to file ARIA-related bugs</a></li> <li class="toggle"> <details><summary>ARIA states and properties</summary> {{ListSubpagesForSidebar("Web/Accessibility/ARIA/Attributes", 1)}} </details> </li> <li class="toggle"> <details><summary>WAI-ARIA Roles</summary> {{ListSubpagesForSidebar("Web/Accessibility/ARIA/Roles", 1)}} </details> </li> </ol> </section> Using JavaScript, it is possible to dynamically change parts of a page without requiring the entire page to reload — for instance, to update a list of search results on the fly, or to display a discreet alert or notification which does not require user interaction. While these changes are usually visually apparent to users who can see the page, they may not be obvious to users of assistive technologies. ARIA live regions fill this gap and provide a way to programmatically expose dynamic content changes in a way that can be announced by assistive technologies. > **Note:** Assistive technologies will announce _dynamic_ changes in the content of a live region. > Including an `aria-live` attribute or a specialized live region `role` (such as [`role="alert"`](/en-US/docs/Web/Accessibility/ARIA/Roles/alert_role)) on the element you want to announce changes to works as long as you add the attribute before the changes occur — either in the original markup, or dynamically using JavaScript. ## Live regions Dynamic content which updates without a page reload is generally either a region or a widget. Simple content changes which are not interactive should be marked as live regions. A live region is explicitly denoted using the `aria-live` attribute. **`aria-live`**: The `aria-live=POLITENESS_SETTING` is used to set the priority with which screen reader should treat updates to live regions - the possible settings are: `off`, `polite` or `assertive`. The default setting is `off`. This attribute is by far the most important. Normally, only `aria-live="polite"` is used. Any region which receives updates that are important for the user to receive, but not so rapid as to be annoying, should receive this attribute. The screen reader will speak changes whenever the user is idle. `aria-live="assertive"` should only be used for time-sensitive/critical notifications that absolutely require the user's immediate attention. Generally, a change to an assertive live region will interrupt any announcement a screen reader is currently making. As such, it can be extremely annoying and disruptive and should only be used sparingly. As `aria-live="off"` is the assumed default for elements, it should not be necessary to set this explicitly, unless you're trying to suppress the announcement of elements which have an implicit live region role (such as `role="alert"`). ### Basic example: Dropdown box updates useful onscreen information A website specializing in providing information about planets provides a dropdown box. When a planet is selected from the dropdown, a region on the page is updated with information about the selected planet. ```html <fieldset> <legend>Planet information</legend> <label for="planetsSelect">Planet:</label> <select id="planetsSelect" aria-controls="planetInfo"> <option value="">Select a planet…</option> <option value="mercury">Mercury</option> <option value="venus">Venus</option> <option value="earth">Earth</option> <option value="mars">Mars</option> </select> <button id="renderPlanetInfoButton">Go</button> </fieldset> <div role="region" id="planetInfo" aria-live="polite"> <h2 id="planetTitle">No planet selected</h2> <p id="planetDescription">Select a planet to view its description</p> </div> <p> <small> Information from <a href="https://en.wikipedia.org/wiki/Solar_System">Wikipedia</a> </small> </p> ``` ```js const PLANETS_INFO = { mercury: { title: "Mercury", description: "Mercury is the smallest and innermost planet in the Solar System. It is named after the Roman deity Mercury, the messenger to the gods.", }, venus: { title: "Venus", description: "Venus is the second planet from the Sun. It is named after the Roman goddess of love and beauty.", }, earth: { title: "Earth", description: "Earth is the third planet from the Sun and the only object in the Universe known to harbor life.", }, mars: { title: "Mars", description: 'Mars is the fourth planet from the Sun and the second-smallest planet in the Solar System after Mercury. In English, Mars carries a name of the Roman god of war, and is often referred to as the "Red Planet".', }, }; function renderPlanetInfo(planet) { const planetTitle = document.querySelector("#planetTitle"); const planetDescription = document.querySelector("#planetDescription"); if (planet in PLANETS_INFO) { planetTitle.textContent = PLANETS_INFO[planet].title; planetDescription.textContent = PLANETS_INFO[planet].description; } else { planetTitle.textContent = "No planet selected"; planetDescription.textContent = "Select a planet to view its description"; } } const renderPlanetInfoButton = document.querySelector( "#renderPlanetInfoButton", ); renderPlanetInfoButton.addEventListener("click", (event) => { const planetsSelect = document.querySelector("#planetsSelect"); const selectedPlanet = planetsSelect.options[planetsSelect.selectedIndex].value; renderPlanetInfo(selectedPlanet); }); ``` {{EmbedLiveSample('Basic_example_Dropdown_box_updates_useful_onscreen_information', '', 350)}} As the user selects a new planet, the information in the live region will be announced. Because the live region has `aria-live="polite"`, the screen reader will wait until the user pauses before announcing the update. Thus, moving down in the list and selecting another planet will not announce updates in the live region. Updates in the live region will only be announced for the planet finally chosen. Here is a screenshot of VoiceOver on Mac announcing the update (via subtitles) to the live region: ![A screenshot of VoiceOver on Mac announcing the update to a live region. Subtitles are shown in the picture.](web_accessibility_aria_aria_live_regions.png) ## Roles with implicit live region attributes Elements with the following [`role="…"`](/en-US/docs/Web/Accessibility/ARIA/Roles) values act as live regions by default: <table style="width: 100%;"> <thead> <tr> <th scope="col">Role</th> <th scope="col">Description</th> <th scope="col">Compatibility Notes</th> </tr> </thead> <tbody> <tr> <td>log</td> <td>Chat, error, game or other type of log</td> <td>To maximize compatibility, add a redundant <code>aria-live="polite"</code> when using this role.</td> </tr> <tr> <td>status</td> <td>A status bar or area of the screen that provides an updated status of some kind. Screen reader users have a special command to read the current status.</td> <td>To maximize compatibility, add a redundant <code>aria-live="polite"</code> when using this role.</td> </tr> <tr> <td>alert</td> <td>Error or warning message that flashes on the screen. Alerts are particularly important for client side validation notices to users. <a href="https://www.w3.org/WAI/ARIA/apg/example-index/alert/alert.html" class="external" rel=" noopener">Alert Example.</a></td> <td>To maximize compatibility, some people recommend adding a redundant <code>aria-live="assertive"</code> when using this role. However, adding both <code>aria-live</code> and <code>role="alert"</code> causes double speaking issues in VoiceOver on iOS.</td> </tr> <tr> <td>progressbar</td> <td>A hybrid between a widget and a live region. Use this with <code>aria-valuemin</code>, <code>aria-valuenow</code> and <code>aria-valuemax</code>. (TBD: add more info here).</td> <td></td> </tr> <tr> <td>marquee</td> <td>Text which scrolls, such as a stock ticker.</td> <td></td> </tr> <tr> <td>timer</td> <td>Any kind of timer or clock, such as a countdown timer or stopwatch readout.</td> <td></td> </tr> </tbody> </table> ## Additional live region attributes Live Regions are well supported. The Paciello Group, in 2014, posted [information about the state of the support of Live Regions](https://www.tpgi.com/screen-reader-support-aria-live-regions/). Paul J. Adam has researched [the support of `aria-atomic` and `aria-relevant`](https://pauljadam.com/demos/aria-atomic-relevant.html) in particular. 1. **`aria-atomic`**: The `aria-atomic=BOOLEAN` is used to set whether or not the screen reader should always present the live region as a whole, even if only part of the region changes. The possible settings are: `false` or `true`. The default setting is `false`. 2. [**`aria-relevant`**](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-relevant) : The `aria-relevant=[LIST_OF_CHANGES]` is used to set what types of changes are relevant to a live region. The possible settings are one or more of: `additions`, `removals`, `text`, `all`. The default setting is: `additions text`. ### Basic examples: `aria-atomic` As an illustration of `aria-atomic`, consider a site with a simple clock, showing hours and minutes. The clock is updated each minute, with the new remaining time overwriting the current content. ```html <div id="clock" role="timer" aria-live="polite"> <span id="clock-hours"></span> <span id="clock-mins"></span> </div> ``` ```js /* basic JavaScript to update the clock */ function updateClock() { const now = new Date(); document.getElementById("clock-hours").textContent = now.getHours(); document.getElementById("clock-mins").textContent = `0${now.getMinutes()}`.substr(-2); } /* first run */ updateClock(); /* update every minute */ setInterval(updateClock, 60000); ``` The first time the function executes, the entirety of the string that is added will be announced. On subsequent calls, only the parts of the content that changed compared to the previous content will be announced. For instance, when the clock changes from "17:33" to "17:34", assistive technologies will only announce "34", which won't be very useful to users. One way around this would be to first clear all the contents of the live region (in this case, set the `innerHTML` of both `<span id="clock-hours">` and `<span id="clock-mins">` to be empty), and then inject the new content. However, this can sometimes be unreliable, as it's dependent on the exact timing of these two updates. `aria-atomic="true"` ensures that each time the live region is updated, the entirety of the content is announced in full (e.g. "17:34"). ```html <div id="clock" role="timer" aria-live="polite" aria-atomic="true">…</div> ``` Another example of `aria-atomic` - an update/notification made as a result of a user action. ```html <div id="date-input"> <label for="year">Year:</label> <input type="text" id="year" value="1990" onblur="change(event)" /> </div> <div id="date-output" aria-atomic="true" aria-live="polite"> The set year is: <span id="year-output">1990</span> </div> ``` ```js function change(event) { const yearOut = document.getElementById("year-output"); switch (event.target.id) { case "year": yearOut.innerHTML = event.target.value; break; default: return; } } ``` Without `aria-atomic="true"` the screen reader announces only the changed value of year. With `aria-atomic="true"`, the screen reader announces "The set year is: _changed value_" ### Basic example: `aria-relevant` With `aria-relevant` you can specify which types of changes/updates to a live region should be announced. As an example, consider a chat site that wants to display a list of users currently logged in. Rather than just announcing the users that are currently logged in, we also want to trigger an announcement specifically when a user is _removed_ from the list. We can achieve this by specifying `aria-relevant="additions removals"`. ```html <ul id="roster" aria-live="polite" aria-relevant="additions removals"> <!-- use JavaScript to add and remove users here --> </ul> ``` Breakdown of ARIA live properties: - `aria-live="polite"` indicates that the screen reader should wait until the user is idle before presenting updates to the user. This is the most commonly used value, as interrupting the user with "assertive" might interrupt their flow. - `aria-atomic` is not set (`false` by default) so that only the added or removed users should be spoken and not the entire roster each time. - `aria-relevant="additions removals"` ensures that both users added or removed to the roster will be spoken. ## See also - [ARIA roles](/en-US/docs/Web/Accessibility/ARIA/Roles)
0
data/mdn-content/files/en-us/web/accessibility
data/mdn-content/files/en-us/web/accessibility/understanding_wcag/index.md
--- title: Understanding the Web Content Accessibility Guidelines slug: Web/Accessibility/Understanding_WCAG page-type: guide --- {{QuicklinksWithSubPages}} This set of articles provides quick explanations to help you understand the steps that need to be taken to conform to the recommendations outlined in the W3C Web Content Accessibility Guidelines 2.0 or 2.1 (or just WCAG, for the purposes of this writing). The WCAG 2.0 and 2.1 provide a detailed set of guidelines for making web content more accessible to people with a wide variety of disabilities. It is comprehensive but incredibly detailed, and quite difficult to gain a rapid understanding of. For this reason, we have summarized the practical steps you need to take to satisfy the different recommendations, with further links to more details where required. ## The four principles WCAG is broadly broken down into four principles — major things that web content **must be** to be considered accessible (see [Understanding the Four Principles of Accessibility](https://www.w3.org/TR/UNDERSTANDING-WCAG20/intro.html#introduction-fourprincs-head) for the WCAG definitions). Each of the links below will take you to pages that further expand on these areas, giving you practical advice on how to write your web content so it conforms to the success criteria outlined in each of the WCAG 2.0 and 2.1 guidelines that further sub-divides each principle. - [Perceivable:](/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable) Users must be able to perceive it in some way, using one or more of their senses. - [Operable](/en-US/docs/Web/Accessibility/Understanding_WCAG/Operable): Users must be able to control UI elements (e.g. buttons must be clickable in some way — mouse, keyboard, voice command, etc.). - [Understandable](/en-US/docs/Web/Accessibility/Understanding_WCAG/Understandable): The content must be understandable to its users. - [Robust](/en-US/docs/Web/Accessibility/Understanding_WCAG/Robust): The content must be developed using well-adopted web standards that will work across different browsers, now and in the future. ## Should I use WCAG 2.0 or 2.1? WCAG 2.1 is the most recent and relevant accessibility standard. Use WCAG 2.1 to help more people with disabilities and reduce the future legal risk for website owners. Target WCAG 2.0 first when allocating resources. Then step up to WCAG 2.1. ### What is WCAG 2.1? WCAG 2.1 was published as an official recommendation on 05 June 2018. The European Union (EU) adopted WCAG 2.1 as the digital accessibility standard in September 2018. W3C published a press release [WCAG 2.1 Adoption in Europe](https://www.w3.org/blog/2018/09/wcag-2-1-adoption-in-europe/). WCAG 2.1 includes: - all of WCAG 2.0 (verbatim, word-for-word) - 17 new Success Criteria at the A / AA / AAA levels primarily addressing user needs in these areas: - Mobile Accessibility - Low Vision - Cognitive - Read more about WCAG 2.1: - W3C/WAI: [What's new in WCAG 2.1?](https://www.w3.org/WAI/standards-guidelines/wcag/new-in-21/) - Deque: [WCAG 2.1: What is Next for Accessibility Guidelines](https://www.deque.com/blog/wcag-2-1-what-is-next-for-accessibility-guidelines/) - TPG: [Web Content Accessibility Guidelines (WCAG) 2.1](https://www.tpgi.com/web-content-accessibility-guidelines-wcag-2-1/) ## Legal standing This guide is intended to provide practical information to help you build better, more accessible websites. However, we are not lawyers, and none of this constitutes legal advice. If you are worried about the legal implications of web accessibility, we'd recommend that you check the specific legislation governing accessibility for the web/public resources in your country or locale, and seek the advice of a qualified lawyer. [What is accessibility?](/en-US/docs/Learn/Accessibility/What_is_accessibility) and particularity the [Accessibility guidelines and the law](/en-US/docs/Learn/Accessibility/What_is_accessibility#accessibility_guidelines_and_the_law) section provide more related information.
0
data/mdn-content/files/en-us/web/accessibility/understanding_wcag
data/mdn-content/files/en-us/web/accessibility/understanding_wcag/robust/index.md
--- title: Robust slug: Web/Accessibility/Understanding_WCAG/Robust page-type: guide --- {{QuicklinksWithSubPages("Web/Accessibility/Understanding_WCAG")}} This article provides practical advice on how to write your web content so that it conforms to the success criteria outlined in the **Robust** principle of the Web Content Accessibility Guidelines (WCAG) 2.0 and 2.1. Robust states that content must be robust enough that it can be interpreted reliably by a wide variety of user agents, including assistive technologies. This can generally be achieved by following web standards and [testing rigorously](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing). > **Note:** To read the W3C definitions for Robust and its guidelines and success criteria, see [Principle 4: Robust — Content must be robust enough that it can be interpreted reliably by a wide variety of user agents, including assistive technologies.](https://www.w3.org/TR/WCAG21/#robust) ## Guideline 4.1 — Compatible: Maximize compatibility with current and future user agents, including assistive technologies This guideline focuses on making content as compatible as possible, not only with current user agents (e.g. browsers), but also with future ones too. <table class="standard-table"> <thead> <tr> <th scope="col">Success criteria</th> <th scope="col">How to conform to the criteria</th> <th scope="col">Practical resource</th> </tr> </thead> <tbody> <tr> <td>4.1.1 Parsing (A)</td> <td> <p> Content should be well-formed so it can be parsed successfully by browsers and other user agents such as screen readers. </p> <p> To pass this criterion, make sure that your HTML is as valid as possible. Use the <a href="https://validator.w3.org/">W3C validator</a> to validate your markup. </p> </td> <td> See <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML/Debugging_HTML" >Debugging HTML</a > for a practical guide. </td> </tr> <tr> <td>4.1.2 Name, Role, Value (A)</td> <td> <p> The name and role of user interface components (e.g. form inputs, buttons, links, etc.) should be programmatically determinable. </p> <p> When using semantic elements correctly for their intended purpose, this criterion should be passed automatically. When scripting custom components, you will need to use WAI-ARIA roles and other features to make sure your controls will be interpreted and are able to be used as intended, e.g. not only by sighted mouse users, but also by screen reader users, keyboard-only users, etc. </p> </td> <td> See <a href="/en-US/docs/Learn/Accessibility/HTML" >HTML: A good basis for accessibility</a > and <a href="/en-US/docs/Learn/Accessibility/WAI-ARIA_basics" >WAI-ARIA basics</a >. </td> </tr> <tr> <td> 4.1.3 Status Messages (AA) <em ><a href="https://www.w3.org/TR/WCAG21/#new-features-in-wcag-2-1" rel="noopener" >added in 2.1</a ></em > </td> <td> <p> Assistive technology users are made aware of new status messages added to the page. </p> </td> <td> <a href="https://www.w3.org/WAI/WCAG21/Understanding/status-messages.html" >Understanding Status Messages</a > </td> </tr> </tbody> </table> > **Note:** Also see the WCAG description for [Guideline 4.1: Compatible: Maximize compatibility with current and future user agents, including assistive technologies.](https://www.w3.org/TR/WCAG21/#compatible) ## See also - [WCAG](/en-US/docs/Web/Accessibility/Understanding_WCAG) 1. [Perceivable](/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable) 2. [Operable](/en-US/docs/Web/Accessibility/Understanding_WCAG/Operable) 3. [Understandable](/en-US/docs/Web/Accessibility/Understanding_WCAG/Understandable) 4. Robust
0
data/mdn-content/files/en-us/web/accessibility/understanding_wcag
data/mdn-content/files/en-us/web/accessibility/understanding_wcag/understandable/index.md
--- title: Understandable slug: Web/Accessibility/Understanding_WCAG/Understandable page-type: guide --- {{QuicklinksWithSubPages("Web/Accessibility/Understanding_WCAG")}} This article provides practical advice on how to write your web content so that it conforms to the success criteria outlined in the **Understandable** principle of the Web Content Accessibility Guidelines (WCAG) 2.0 and 2.1. Understandable states that information and the operation of user interface must be understandable. > **Note:** To read the W3C definitions for Understandable and its guidelines and success criteria, see [Principle 3: Understandable — Information and the operation of user interface must be understandable](https://www.w3.org/TR/WCAG21/#understandable). ## Guideline 3.1 — Readable: Make text content readable and understandable This guideline focuses on making text content as understandable as possible. <table class="standard-table"> <thead> <tr> <th scope="col">Success criteria</th> <th scope="col">How to conform to the criteria</th> <th scope="col">Practical resource</th> </tr> </thead> <tbody> <tr> <td>3.1.1 Language of Page (A)</td> <td> The default human language of each web page should be detectable via code. This is essential for purposes like making sure the reader has arrived at a page written in a language suitable for them. The simplest way to achieve this is to set the <a href="/en-US/docs/Web/HTML/Global_attributes#lang">lang</a> attribute on the page's {{htmlelement("html")}} element, giving it a value equal to the language code that best represents the language the page is written in. </td> <td> See <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML#setting_the_primary_language_of_the_document" >Setting the primary language of the document</a >. </td> </tr> <tr> <td>3.1.2 Language of Parts (AA)</td> <td> <p> In cases where the content of a page includes words or phrases that are in a different language to the primary language, use the <a href="/en-US/docs/Web/HTML/Global_attributes#lang">lang</a> attribute on an element wrapped around the term in question (e.g. a {{htmlelement("span")}} if no semantic element is available) to set an appropriate language for it. </p> <p> You don't need to set a different language for words or phrases that are the same regardless of language (for example proper names, technical terms that aren't part of a specific language). </p> </td> <td></td> </tr> <tr> <td>3.1.3 Unusual Words (AAA)</td> <td> Where technical terms, jargon, or idioms/slang are used, definitions should be provided for such phrases/words. Your site should provide a glossary that contains definitions of such words/terms that you can then link to when they appear, or at the very least provide definitions somewhere in the surrounding text, or in a <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML/Advanced_text_formatting#description_lists" >description list</a > at the bottom of the page. </td> <td></td> </tr> <tr> <td>3.1.4 Abbreviations (AAA)</td> <td> <p> Where abbreviations are used, you should provide an expansion of them, or a definition as required. </p> <p> The {{htmlelement("abbr")}} element is often thought of as the preferred way to provide an expansion for an abbreviation — it takes a <a href="/en-US/docs/Web/HTML/Global_attributes#title">title</a> attribute that contains the expansion, and this appears when the acronym is moused over. However, the title contents are not accessible via keyboard, nor are they reliably read out by screen readers. A better way to handle this is to again provide links to glossary pages containing the acronym expansion and explanation, or at the very least include them in the surrounding text in context. </p> </td> <td> See <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML/Advanced_text_formatting#abbreviations" >Abbreviations</a >. </td> </tr> <tr> <td>3.1.5 Reading Level (AAA)</td> <td> <p> If text is provided that requires a higher reading level that lower secondary education level (typically children around 11-14 years old), provide supplementary explainer material to help people who can't read it, or provide an alternative version that is written at lower secondary level. </p> <p> This doesn't mean that all subject matter should be understood by everyone, but that the style of writing should be accessible by everyone. It is better to just write all content at lower secondary level, even technical documentation like programming tutorials, unless there is a good reason not to (e.g. an alternative style for poetic effect), or they have to be written in a strict style (e.g. W3C specs). </p> </td> <td></td> </tr> <tr> <td>3.1.6 Pronunciation (AAA)</td> <td> <p> A mechanism should be provided to give users access to pronunciation of words where they are is needed to understand the content fully. </p> <p> The HTML {{htmlelement("audio")}} element can be used to create a control that allows the reader to play back an audio file containing the correct pronunciation, and it also makes sense to include a textual pronunciation guide after difficult words, in the same way that you find in dictionary entries. </p> </td> <td> See <a href="/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content" >Video and audio content</a >, and <a href="http://www.oxfordlearnersdictionaries.com/us/about/pronunciation_english.html" >Pronunciation Guide for English Dictionary</a > </td> </tr> </tbody> </table> > **Note:** Also see the WCAG description for [Guideline 3.1 Readable: Make text content readable and understandable](https://www.w3.org/TR/WCAG21/#readable). ## Guideline 3.2 — Predictable: Make Web pages appear and operate in predictable ways This guideline focuses on making user interfaces intuitive and understandable. <table class="standard-table"> <thead> <tr> <th scope="col">Success criteria</th> <th scope="col">How to conform to the criteria</th> <th scope="col">Practical resource</th> </tr> </thead> <tbody> <tr> <td>3.2.1 On Focus (A)</td> <td> <p> When a control or other page feature receives focus, it should not change the context in a way that may confuse or disorientate the user. </p> <p> This is a matter of sensible design — people don't want interfaces to surprise them; they want things to be intuitive and behave as expected. For example, focusing a navigation menu option should not change the displayed page — it should be activated before the display changes. </p> </td> <td> {{domxref("Element.focus_event")}} contains some useful information. Also see <a href="/en-US/docs/Learn/Accessibility/HTML#building_keyboard_accessibility_back_in" >Building keyboard accessibility back in</a > for some useful implementation ideas. </td> </tr> <tr> <td>3.2.2 On Input (A)</td> <td> <p> When data is inputted into a control, or a setting is changed, context should not be changed unexpectedly. The user should be warned/advised of the impending change before it occurs. </p> <p> Again, sensible design should be implemented. For example, if pressing a button causes the application to exit the current view, the user should be asked to confirm this action, save their work if appropriate, etc. </p> </td> <td> The {{domxref("Element/input_event", "input")}} event is useful here. </td> </tr> <tr> <td>3.2.3 Consistent Navigation (AA)</td> <td> <p> Navigation menu/control style and positioning should be consistent between different pages or views of a web page, and the existing items should appear in the same order, even if for example new items are added. If the user has initiated a change, e.g. choosing a different color scheme or position for the navigation, their choice should be respected across all pages. </p> <p> Again, sensible design — make the navigation controls the same across all pages or views. </p> </td> <td> See <a href="/en-US/docs/Learn/Accessibility/HTML#page_layouts" >Page layouts</a > for information on modern markup for layouts. See also <a href="/en-US/docs/Learn/CSS/Styling_text/Styling_links#styling_links_as_buttons" >Styling links as buttons</a > for a useful accessible navigation menu example. </td> </tr> <tr> <td>3.2.4 Consistent Identification (AA)</td> <td> <p> Controls or components that have the same functionality should be identified in the same way across different pages or views. A currency converter appearing on every page of a world travel site for example should be exactly the same, semantically and in terms of labels. </p> <p>Again, sensible design!</p> </td> <td> "Labels" can refer to descriptive information in text content, or HTML form labels. See <a href="/en-US/docs/Learn/Accessibility/HTML#meaningful_text_labels" >Meaningful text labels</a > for more information. </td> </tr> <tr> <td>3.2.5 Change on Request (AAA)</td> <td> <p> Changes in context that could possibly confuse or disorient users should only occur only when requested by the user, OR the user should be able to turn them off. </p> <p> If you need to have something that significantly changes the current view (e.g. content or controls), let the user control when they want that change to occur (e.g. what page to show, when to advance to the next photo in the gallery...) </p> <p> If you need to have something like a carousel on a page, provide an option to stop it automatically advancing. Better to avoid such functionality if possible. </p> </td> </tr> <tr> <td> 3.2.6 Consistent help (A)</td> <td> <p> Web pages that contain help mechanisms, including self-help options and human contact details, that are repeated on multiple web pages, need to place those mechanisms in the same order on all pages, unless a change is initiated by the user.</p> <td> <p> Check out the <a href="https://www.w3.org/WAI/WCAG22/Understanding/consistent-help">consistent help documentation</a> for this standard to learn more. </p> </td> </td> <tr> </tr> </tbody> </table> > **Note:** Also see the WCAG description for [Guideline 3.2 Predictable: Make Web pages appear and operate in predictable ways](https://www.w3.org/TR/WCAG21/#predictable). ## Guideline 3.3 — Input Assistance: Help users avoid and correct mistakes This guideline centers around helping users enter correct information when required with the minimum of mistakes. <table class="standard-table"> <thead> <tr> <th scope="col">Success criteria</th> <th scope="col">How to conform to the criteria</th> <th scope="col">Practical resource</th> </tr> </thead> <tbody> <tr> <td>3.3.1 Error Identification (A)</td> <td> <p> When a user is filling out a form or choosing between options, any error that is detected should be clearly reported to the user, along with the form control that the error relates to. </p> <p> It is advisable to implement client-side error detection and handling, via HTML form validation features, and/or JavaScript, whatever is best for your situation. When an error is detected, an intuitive error message should be shown next to the form input that is at fault to help the user correct their inputs. For screen reader users, you can use aria live regions to alert the user to a change on the page. </p> <div class="note"> <p> <strong>Note</strong>: Server-side validation should *always* be used alongside client-side validation. Client-side validation is too easy to turn off or otherwise get around, so it can't be relied on alone. </p> </div> </td> <td> See <a href="/en-US/docs/Learn/Forms/Form_validation" >Form data validation</a > for comprehensive validation information, and <a href="/en-US/docs/Learn/Accessibility/WAI-ARIA_basics#dynamic_content_updates" >WAI-ARIA: Dynamic content updates</a > for information on live regions. </td> </tr> <tr> <td>3.3.2 Labels or Instructions (A)</td> <td> <p> Clear instructions should be provided when data input is required. When a simple instruction or prompt is required, you can use {{htmlelement("label")}} elements for single inputs like name or age, a combination or {{htmlelement("label")}}s and {{htmlelement("fieldset")}}s/{{htmlelement("legend")}}s for multiple inputs that go together (like the elements of a date of birth or postal address). </p> <p> When more complex explanation is required, you can always include explanatory paragraphs too, or maybe you need to try to make your forms more intuitive. </p> </td> <td> <ul> <li> <a href="/en-US/docs/Learn/Accessibility/HTML#meaningful_text_labels" >Meaningful text labels</a > </li> <li> <a href="/en-US/docs/Learn/Forms/How_to_structure_a_web_form" >How to structure an HTML form</a > </li> <li> <a href="/en-US/docs/Web/Accessibility/Understanding_WCAG/Text_labels_and_names" >Text labels and names</a > </li> </ul> </td> </tr> <tr> <td>3.3.3 Error Suggestion (AA)</td> <td> <p> When an error is detected and suggestions for correction are known, provide these to the user (e.g. suggesting alternatives when the user is choosing a user name and has selected one that is already taken), unless doing so would cause a security issue (e.g. when entering a password) or context problem (e.g. they are trying to answer a question in a quiz app). </p> <p> In such cases, when this is appropriate, you'll probably use a combination of JavaScript and server-side functionality to check if the entry is correct, and if not, what viable suggestions can be given to the user. Such suggestions should be displayed usefully in context, just like error messages (see 3.3.1). </p> </td> <td>No tutorial suggestions yet.</td> </tr> <tr> <td>3.3.4 Error Prevention (Legal, Financial, Data) (AA)</td> <td> <p> In the case of forms involved with entry of sensitive data (such as legal agreements, e-commerce transactions, or personal data), at least one of the following should be true: </p> <ul> <li>Submissions are reversible.</li> <li> Data is checked for errors, and the user is given an opportunity to correct them. </li> <li> A mechanism is available for confirming and correcting information before final submission. </li> </ul> </td> <td> <p> <strong>Reversible</strong> — for any view where data can be entered, provide an equivalent view that allows you to edit or even delete an entry, as appropriate (for example, see <a href="/en-US/docs/Learn/Server-side/Django">Django web framework</a >). </p> <p> <strong>Checking data</strong> — as covered in 3.3.1, a combination of client-side and server-side validation should be used to detect errors and display helpful messages to the user to allow them to correct their inputs. </p> <p> <strong>Confirm and correct</strong> — where appropriate, after filling in a series of form fields to perform a task (such as buying a product), the user should be shown a confirmation screen where they can review their inputs and correct anything that doesn't look right. This pattern is commonly used on e-commerce sites like Amazon. </p> </td> </tr> <tr> <td>3.3.5 Context-sensitive help is available (AAA)</td> <td> Provide instructions and other appropriate cues in context to aid form completion and submission. </td> <td> This really just builds on 3.3.1 and other similar criteria but requires more thorough contextual help information and services, e.g. providing a dedicated link to a help page or service on each page, providing examples showing what successful completion should look like. </td> </tr> <tr> <td>3.3.6 Error Prevention (All) (AAA)</td> <td> This principle builds on 3.3.4, extending its requirements to all user input situations, not just ones involving sensitive data. </td> <td>Again, see 3.3.4.</td> </tr> <tr> <td> 3.3.7 Redundant entry (A) </td> <td> Information that is required that was previously entered or provided by the user in the same process or user flow is either auto-populated or made selectable to the user from a list of options, unless re-entering the information is essential or required for security reasons, or if the information is no longer valid. </td> <td>Check out <a href="https://www.w3.org/WAI/WCAG22/Understanding/redundant-entry">Understanding redundant entry</a> to learn more.</td> </tr> <tr> <td> 3.3.8 Accessible authentication (Minimum) (AA) </td> <td> Cognitive function tests, like remembering a password, are not required for any step in an authentication process unless an alternative is provided, such as an object or personal content (e.g., images, videos, and audio) recognition, or a mechanism to assist (e.g., copy and paste and autosave passwords). </td> <td> Check out the <a href="https://www.w3.org/WAI/WCAG22/Understanding/accessible-authentication-minimum"> accessible authentication documentation</a> for this standard to learn more. </td> </tr> <tr> <td> 3.3.9 Accessible Authentication (Enhanced) (AAA) </td> <td> A cognitive function test, like remembering a password, must not be required for any step in an authentication process without providing an alternative that does not rely on a cognitive function test or provides a mechanism to assist the user in completing the cognitive function test. Authentication tests that require the user to recognize objects or identify non-text content the user provided to the website are allowed. </td> <td> Check out the <a href="https://www.w3.org/WAI/WCAG22/Understanding/accessible-authentication-enhanced">enhanced accessible authentication documentation (AAA)</a> to learn more.</td> </tr> </tbody> </table> > **Note:** Also see the WCAG description for [Guideline 3.3 Input Assistance: Help users avoid and correct mistakes](https://www.w3.org/TR/WCAG21/#input-assistance). ## See also - [WCAG](/en-US/docs/Web/Accessibility/Understanding_WCAG) 1. [Perceivable](/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable) 2. [Operable](/en-US/docs/Web/Accessibility/Understanding_WCAG/Operable) 3. Understandable 4. [Robust](/en-US/docs/Web/Accessibility/Understanding_WCAG/Robust)
0
data/mdn-content/files/en-us/web/accessibility/understanding_wcag
data/mdn-content/files/en-us/web/accessibility/understanding_wcag/perceivable/index.md
--- title: Perceivable slug: Web/Accessibility/Understanding_WCAG/Perceivable page-type: guide --- {{QuicklinksWithSubPages("Web/Accessibility/Understanding_WCAG")}} This article provides practical advice on how to write your web content so that it conforms to the success criteria outlined in the **Perceivable** principle of the Web Content Accessibility Guidelines (WCAG) 2.0 and 2.1. Perceivable states that users must be able to perceive it in some way, using one or more of their senses. > **Note:** To read the W3C definitions for Perceivable and its guidelines and success criteria, see [Principle 1: Perceivable - Information and user interface components must be presentable to users in ways they can perceive.](https://www.w3.org/TR/WCAG21/#perceivable) ## Guideline 1.1 — Providing text alternatives for non-text content The key here is that text can be converted to other forms that people with disabilities can use. For example, it can be spoken by a screen reader, converted to large print, or represented on a braille display. Non-text content refers to multimedia such as images, audio, and video. <table class="standard-table"> <thead> <tr> <th scope="col">Success criteria</th> <th scope="col">How to conform to the criteria</th> <th scope="col">Practical resource</th> </tr> </thead> <tbody> <tr> <td rowspan="5">1.1.1 Provide text equivalents (A)</td> <td> All images that convey meaningful content should be given suitable alternative text. </td> <td> <a href="/en-US/docs/Learn/Accessibility/HTML#text_alternatives" >Text alternatives.</a > </td> </tr> <tr> <td> Complex images or charts should have an accessible alternative provided, either on the same page or via a link. Use a regular link instead of a `longdesc` attribute. </td> <td> <p> A text description may work, or an accessible data table (see <a href="/en-US/docs/Learn/HTML/Tables/Advanced" >HTML table advanced features and accessibility</a >). See <a href="/en-US/docs/Learn/Accessibility/HTML#other_text_alternative_mechanisms" >Other text alternative mechanisms</a > for the argument against `longdesc`. </p> </td> </tr> <tr> <td> Multimedia content (i.e., audio or video) should at least have a descriptive identification available, such as a caption or similar. </td> <td> <p> See <a href="/en-US/docs/Learn/Accessibility/HTML#text_alternatives" >Text alternatives</a > for static caption options, and <a href="/en-US/docs/Learn/Accessibility/Multimedia#audio_transcripts" >Audio transcripts</a >, <a href="/en-US/docs/Learn/Accessibility/Multimedia#video_text_tracks" >Video text tracks</a >, and <a href="/en-US/docs/Learn/Accessibility/Multimedia#other_multimedia_content" >Other multimedia content</a > for other alternatives. </p> </td> </tr> <tr> <td> UI controls such as form elements and buttons should have text labels that describe their purpose. </td> <td> Buttons are simple—you should make sure the button text describes the function of the button (e.g., <code >&#x3C;button>Upload image&#x3C;/button></code >). For more information on other UI controls, see <a href="/en-US/docs/Learn/Accessibility/HTML#ui_controls" >UI controls</a >. </td> </tr> <tr> <td> Implement decorative (non-content) images, video, etc., in a way that is invisible to assistive technology, so it doesn't confuse users. </td> <td> <p> Decorative images should be implemented using CSS background images (see <a href="/en-US/docs/Learn/CSS/Building_blocks/Backgrounds_and_borders" >Backgrounds</a >). If you have to include an image via an {{htmlelement("img")}} element, give it a blank alt (<code>alt=""</code>). Otherwise, screen readers may try to read out the filepath, etc. </p> <p> If you are including background video or audio that autoplays, make it as unobtrusive as possible. Don't make it look/sound like content, and provide a control to turn it off. Ideally, don't include it at all. </p> </td> </tr> </tbody> </table> > **Note:** Also see the [WCAG description for Guideline 1.1: Text alternatives](https://www.w3.org/TR/WCAG21/#text-alternatives). ## Guideline 1.2 — Providing text alternatives for time-based media Time-based media refers to multimedia with a duration, such as audio and video. Note that if the audio/video serves as an alternative to existing text content, you don't need to provide another text alternative. <table> <thead> <tr> <th scope="col">Success criteria</th> <th scope="col">How to conform to the criteria</th> <th scope="col">Practical resource</th> </tr> </thead> <tbody> <tr> <td>1.2.1 Provide alternatives for pre-recorded audio-only and video-only content (A)</td> <td>A transcript should be provided for prerecorded audio-only media, and a transcript or audio description should be provided for prerecorded video-only media (i.e., silent video).</td> <td>See&nbsp;<a href="/en-US/docs/Learn/Accessibility/Multimedia#audio_transcripts">Audio transcripts</a> for transcript information. No audio description tutorial is available yet.</td> </tr> <tr> <td>1.2.2 Provide captions for web-based video (A)</td> <td>You should provide captions for video presented on the web (e.g., HTML video). This is for the benefit of people who can't hear the audio part of the video.</td> <td>See <a href="/en-US/docs/Learn/Accessibility/Multimedia#video_text_tracks">Video text tracks</a> for HTML video captions, and <a href="/en-US/docs/Learn/Accessibility/Multimedia#other_multimedia_content">Other multimedia content</a> for other technologies. See also <a href="https://support.google.com/youtube/answer/2734796?hl=en">Add your own subtitles &amp; closed captions</a> (YouTube).</td> </tr> <tr> <td>1.2.3 Provide text transcript or audio description for web-based video (A)</td> <td>You should provide text transcripts or audio descriptions for video presented on the web (e.g., HTML video. This is for the benefit of people who can't see the visual part of the video, and don't get the full content from the audio alone.</td> <td>See&nbsp;<a href="/en-US/docs/Learn/Accessibility/Multimedia#audio_transcripts">Audio transcripts</a> for transcript information. No audio description tutorial is available yet.</td> </tr> <tr> <td>1.2.4 Provide captions for live audio (AA)</td> <td>You should provide synchronized captions for all live multimedia that contains audio (e.g., video conferences, live audio broadcasts).</td> <td></td> </tr> <tr> <td>1.2.5 Provide audio descriptions for prerecorded video (AA)</td> <td>Audio descriptions should be provided for prerecorded video, but only where the existing audio does not convey the full meaning expressed by the video.</td> <td></td> </tr> <tr> <td>1.2.6 Provide sign language equivalent to prerecorded audio (AAA)</td> <td>An equivalent sign language video should be provided for any prerecorded content containing audio.</td> <td></td> </tr> <tr> <td>1.2.7 Provide extended video with audio descriptions (AAA)</td> <td>Where audio descriptions cannot be provided (see 1.2.5) due to video timing issues (e.g., there are no suitable pauses in the content in which to insert the audio descriptions), an alternative version of the video should be provided that includes inserted pauses (and audio descriptions).</td> <td></td> </tr> <tr> <td>1.2.8 Provide an alternative for prerecorded media (AAA)</td> <td>For all content that features video, a descriptive text transcript should be provided, for example a script of the movie you are watching. This is for the benefit of hearing-impaired viewers who cannot hear the content.</td> <td>See&nbsp;<a href="/en-US/docs/Learn/Accessibility/Multimedia#audio_transcripts">Audio transcripts</a> for transcript information.</td> </tr> <tr> <td>1.2.9 Provide a transcript for live audio (AAA)</td> <td>For any live audio content being broadcast, a descriptive text should be provided, for example a script of the play or musical you are listening to. This is for the benefit of hearing-impaired viewers who cannot hear the content.</td> <td>See&nbsp;<a href="/en-US/docs/Learn/Accessibility/Multimedia#audio_transcripts">Audio transcripts</a> for transcript information.</td> </tr> </tbody> </table> > **Note:** Also see the [WCAG description for Guideline 1.2: Time-based Media: Provide alternatives for time-based media](https://www.w3.org/TR/WCAG21/#time-based-media). ## Guideline 1.3 — Create content that can be presented in different ways This guideline refers to the ability of content to be consumed by users in multiple ways, accommodating their differing needs. <table class="standard-table"> <tbody> <tr> <th scope="col">Success criteria</th> <th scope="col">How to conform to the criteria</th> <th scope="col">Practical resource</th> </tr> <tr> <td>1.3.1 Info and relationships (A)</td> <td> <p> Any content structure—or visual relationship made between content—can also be determined programmatically, or be inferred from text description. The main situations in which this is relevant are: </p> <ul> <li> Text labels and the form elements they describe. These are associated unambiguously using the {{htmlelement("label")}} element, which can be picked up by screen readers, etc. </li> <li> Image alt text. Content images should have text available that clearly describes the image's contents, which can be programmatically associated with it (e.g., `alt` text), or otherwise is easy to associate (e.g., describes it and is sat right next to it). This should mean that the full meaning can still be inferred even if you can't see the image. </li> <li> Lists. If the order of list items is important, use an ordered list ({{htmlelement("ol")}}). </li> </ul> </td> <td> The whole of <p> <a href="/en-US/docs/Learn/Accessibility/HTML" >HTML: A good basis for accessibility</a > is packed with information about this, but you should particularly refer to <a href="/en-US/docs/Learn/Accessibility/HTML#good_semantics" >Good semantics</a >, <a href="/en-US/docs/Learn/Accessibility/HTML#ui_controls" >UI controls</a >, and <a href="/en-US/docs/Learn/Accessibility/HTML#text_alternatives" >Text alternatives</a >. </p> </td> </tr> <tr> <td>1.3.2 Meaningful content sequence (A)</td> <td> A sensible, logical reading order should be easy to determine for any content, even if it is visually presented in an unusual way. The order should be made obvious by use of correct semantic elements (e.g., headings, paragraphs), with CSS being used to create any unusual layout styles, irrespective of the markup. </td> <td> Again, refer to <a href="/en-US/docs/Learn/Accessibility/HTML" >HTML: A good basis for accessibility</a >. </td> </tr> <tr> <td>1.3.3 Sensory characteristics (A)</td> <td> <p> Instructions for operating controls or understanding content do not rely on a single sense. This may prove inaccessible to people with a disability related to that sense, or a device that does not support that sense. So, for example: </p> <ul> <li> "Click the round button to continue"<br />The button should be clearly labelled so that it is obvious that it is the button you need to press. If there are multiple buttons, make sure they are all clearly labelled to distinguish their function. </li> <li> "Listen to the audio instructions for guidance"<br />This is obviously problematic—audio will be inaccessible to those with hearing impairments, whereas text can be read, but also spoken by a screen reader if required. </li> <li> "Swipe from the right-hand side of the screen to reveal the menu"<br />Some users might not be able to swipe the screen, either due to disability or because their device does not support touch. An alternative should be provided, such as a keyboard shortcut or button that can be activated by keyboard or other means. </li> </ul> <div class="note"> <p> <strong>Note:</strong> Conveying instructions solely by color is related, but covered in a different guideline — 1.4.1. </p> </div> </td> <td></td> </tr> <tr> <td> 1.3.4 Orientation (AA) <em ><a href="https://www.w3.org/TR/WCAG21/#new-features-in-wcag-2-1" >added in 2.1</a ></em > </td> <td> Content does not restrict its view and operation to a single display orientation, such as portrait or landscape, unless a specific display orientation is essential. </td> <td> <p> <a href="https://www.w3.org/WAI/WCAG21/Understanding/orientation.html" >Understanding Orientation</a > </p> </td> </tr> <tr> <td> 1.3.5 Identify Input Purpose (AA) <em ><a href="https://www.w3.org/TR/WCAG21/#new-features-in-wcag-2-1" >added in 2.1</a ></em > </td> <td> <p> Follow the list of <a href="https://www.w3.org/TR/WCAG21/#input-purposes" >53 input fields</a > to programmatically identify the purpose of a field. </p> </td> <td> <a href="https://www.w3.org/WAI/WCAG21/Understanding/identify-input-purpose.html" >Understanding Identify Input Purpose</a > </td> </tr> <tr> <td> 1.3.6 Identify Purpose (AAA) <em ><a href="https://www.w3.org/TR/WCAG21/#new-features-in-wcag-2-1" >added in 2.1</a ></em > </td> <td> In content implemented using markup languages, the purpose of user interface components, icons, and regions can be programmatically determined. </td> <td> <a href="https://www.w3.org/WAI/WCAG21/Understanding/identify-purpose.html" >Understanding Identify Purpose</a > </td> </tr> </tbody> </table> > **Note:** Also see the WCAG description for [Guideline 1.3: Adaptable: Create content that can be presented in different ways without losing information or structure.](https://www.w3.org/TR/WCAG21/#adaptable) ## Guideline 1.4: Make it easier for users to see and hear content including separating foreground from background This guideline relates to making sure core content is easy to discern from backgrounds and other decoration. The classic example is color (both color contrast and use of color to convey instructions), but it applies in other situations too. <table class="standard-table"> <thead> <tr> <th scope="col">Success criteria</th> <th scope="col">How to conform to the criteria</th> <th scope="col">Practical resource</th> </tr> <tr> <td>1.4.1 Use of color (A)</td> <td> <p> Color should not be solely relied upon to convey information. For example, in forms, you should never mark required fields purely with a color (like red). Instead (or as well as), something like an asterisk with a label of "required" would be more appropriate. </p> </td> <td> See <a href="/en-US/docs/Learn/Accessibility/CSS_and_JavaScript#color_and_color_contrast" >Color and color contrast</a > and <a href="/en-US/docs/Learn/Forms/How_to_structure_a_web_form#multiple_labels" >Multiple labels</a >. </td> </tr> <tr> <td>1.4.2 Audio controls (A)</td> <td> For any audio that plays for longer than three seconds, provide accessible controls to play and pause the audio/video, and mute/adjust volume. </td> <td> Use native `&#x3C;button>`s to provide accessible keyboard controls, as shown in <a href="/en-US/docs/Web/Media/Audio_and_video_delivery/Video_player_styling_basics" >Video player styling basics</a >. </td> </tr> <tr> <td>1.4.3 Minimum contrast (AA)</td> <td> <p> The color contrast between background and foreground content should be at a minimum level to ensure legibility: </p> <ul> <li> Text and its background should have a contrast ratio of at least 4.5:1. </li> <li> Heading (or just larger) text should have a ratio of at least 3:1. Larger text is defined as at least 18pt, or 14pt bold. </li> </ul> </td> <td> See <a href="/en-US/docs/Learn/Accessibility/CSS_and_JavaScript#color_and_color_contrast" >Color and color contrast</a >. </td> </tr> <tr> <td>1.4.4 Resize text (AA)</td> <td> The page should be readable and usable when the text size is doubled. This means that designs should be responsive, so that when the text size is increased, the content is still accessible. </td> <td></td> </tr> <tr> <td>1.4.5 Images of text (AA)</td> <td> Images should NOT be used to present content where text would do the job. For example, if an image is mostly textual, it could be represented using text as well as images. </td> <td></td> </tr> <tr> <td>1.4.6 Enhanced contrast (AAA)</td> <td> <p>This follows, and builds on, criterion 1.4.3.</p> <ul> <li> Text and its background should have a contrast ratio of at least 7:1. </li> <li> Heading (or just larger) text should have a ratio of at least 4.5:1. Larger text is defined as at least 18pt, or 14pt bold. </li> </ul> </td> <td> See <a href="/en-US/docs/Learn/Accessibility/CSS_and_JavaScript#color_and_color_contrast" >Color and color contrast</a >. </td> </tr> <tr> <td>1.4.7 Low or no background audio (AAA)</td> <td> Prerecorded audio recordings that primarily feature speech should have minimal background noise, so the content can be easily understood. </td> <td></td> </tr> <tr> <td>1.4.8 Visual presentation (AAA)</td> <td> <p>For text content presentation, the following should be true:</p> <ul> <li>Foreground and background colors should be user-selectable.</li> <li> Text blocks should be no wider than 80 characters (or glyphs), for maximum readability. </li> <li> Text should not be fully justified (e.g., <code >text-align: justify;</code >). </li> <li> Line height should be at least 1.5 times the text size within paragraphs (e.g., `line-height: 1.5;`), and at least 2.25 times the text size between paragraphs (e.g., <code >padding: 2.25rem;</code >). </li> <li> When the text size is doubled, the content should not need to be scrolled. </li> </ul> </td> <td></td> </tr> <tr> <td>1.4.9 Images of text (No Exception) (AAA)</td> <td> Text should not be presented as part of an image unless it is purely decoration (i.e., it does not convey any content) or cannot be presented in any other way. </td> <td></td> </tr> <tr> <td> 1.4.10 Reflow (AA) <em ><a href="https://www.w3.org/TR/WCAG21/#new-features-in-wcag-2-1" >added in 2.1</a ></em > </td> <td> <ul> <li> No horizontal scrolling for left-to-right languages (like English) or right-to-left languages (like Arabic) </li> <li> No vertical scrolling for top-to-bottom languages (like Japanese) </li> <li> Except for parts of the content which require two-dimensional layout for usage or meaning (like a large data table) </li> </ul> </td> <td> <a href="https://www.w3.org/WAI/WCAG21/Understanding/reflow.html" >Understanding Reflow</a > </td> </tr> <tr> <td> 1.4.11 Non-Text Contrast(AA) <em ><a href="https://www.w3.org/TR/WCAG21/#new-features-in-wcag-2-1" >added in 2.1</a ></em > </td> <td> Minimum color contrast ratio of 3:1 for user interface components and graphical objects. </td> <td> <a href="https://www.w3.org/WAI/WCAG21/Understanding/non-text-contrast.html" >Understanding Non-Text Contrast</a > </td> </tr> <tr> <td> 1.4.12 Text Spacing (AA) <em ><a href="https://www.w3.org/TR/WCAG21/#new-features-in-wcag-2-1" >added in 2.1</a ></em > </td> <td> <p> No loss of content or functionality occurs when the following styles are applied: </p> <ul> <li> Line height (line spacing) to at least 1.5 times the font size </li> <li> Spacing following paragraphs to at least 2 times the font size </li> <li> Letter spacing (tracking) to at least 0.12 times the font size </li> <li>Word spacing to at least 0.16 times the font size</li> </ul> </td> <td> <a href="https://www.w3.org/WAI/WCAG21/Understanding/text-spacing.html" >Understanding Text Spacing</a > </td> </tr> <tr> <td> 1.4.13 Content on Hover or Focus (AA) <em ><a href="https://www.w3.org/TR/WCAG21/#new-features-in-wcag-2-1" >added in 2.1</a ></em > </td> <td> <p> While additional content may appear and disappear in coordination with hover and keyboard focus, this success criterion specifies three conditions that must be met: </p> <ul> <li>dismissible (can be closed/removed)</li> <li> hoverable (the additional content does not disappear when the pointer is over it) </li> <li> persistent (the additional content does not disappear without user action) </li> </ul> </td> <td> <a href="https://www.w3.org/WAI/WCAG21/Understanding/content-on-hover-or-focus.html" >Understanding Content on Hover or Focus</a > </td> </tr> </thead> </table> > **Note:** Also see the WCAG description for [Guideline 1.4: Distinguishable: Make it easier for users to see and hear content including separating foreground from background.](https://www.w3.org/TR/WCAG21/#distinguishable) ## See also - [WCAG](/en-US/docs/Web/Accessibility/Understanding_WCAG) 1. Perceivable 2. [Operable](/en-US/docs/Web/Accessibility/Understanding_WCAG/Operable) 3. [Understandable](/en-US/docs/Web/Accessibility/Understanding_WCAG/Understandable) 4. [Robust](/en-US/docs/Web/Accessibility/Understanding_WCAG/Robust)
0
data/mdn-content/files/en-us/web/accessibility/understanding_wcag/perceivable
data/mdn-content/files/en-us/web/accessibility/understanding_wcag/perceivable/color_contrast/index.md
--- title: Color contrast slug: Web/Accessibility/Understanding_WCAG/Perceivable/Color_contrast page-type: guide --- {{QuicklinksWithSubPages("Web/Accessibility/Understanding_WCAG")}} The [color contrast](https://www.w3.org/TR/WCAG21/#dfn-contrast-ratio) between background and foreground content (that is, usually text) should be great enough to ensure legibility. When designing readable interfaces for different vision capabilities, the WCAG guidelines recommend the following contrast ratios: | Type of content | Minimum ratio (AA rating) | Enhanced ratio (AAA rating) | | ------------------------------------------------------------------------------- | ------------------------- | --------------------------- | | Body text | 4.5 : 1 | 7 : 1 | | Large-scale text (120-150% larger than body text) | 3 : 1 | 4.5 : 1 | | Active user interface components and graphical objects such as icons and graphs | 3 : 1 | Not defined | These ratios do not apply to "incidental" text, such as inactive controls, logotypes, or purely decorative text. See the [Solution](#solution) section below for further information. Having good color contrast on your site benefits all your users, but it is particularly beneficial to users with certain types of color blindness and other similar conditions, who experience low contrast, and have trouble differentiating between similar colors. This is because they don't see bright and dark areas as readily as those without such conditions, and therefore have trouble seeing edges, borders, and other details. It is good to have a cool design on your website, but the design is worthless if your users can't read your content. ## Examples Let's have a look at some simple HTML and CSS code: ```html <div class="good">Good contrast</div> <div class="bad">Bad contrast</div> ``` ```css div { /* General div styles here */ } .good { background-color: #5a80a9; } .bad { background-color: #400064; } ``` Both pieces of text have their default black color. ### Good Contrast The "good" `<div>` has a neon blue background, which makes the text easy to read: ```html <div class="good">Good contrast</div> ``` ```css div { font-family: sans-serif; text-align: center; font-size: 2rem; font-weight: bold; width: 250px; padding: 30px; border-radius: 20px; box-shadow: 4px 4px 4px black; } .good { background-color: #5a80a9; } ``` {{EmbedLiveSample('Good_Contrast', '100%', '100')}} ### Bad Contrast The "bad" `<div>` on the other hand has a very dark purple background, which makes the text much harder to read: ```html <div class="bad">Bad contrast</div> ``` ```css div { font-family: sans-serif; text-align: center; font-size: 2rem; font-weight: bold; width: 250px; padding: 30px; border-radius: 20px; box-shadow: 4px 4px 4px black; } .bad { background-color: #400064; } ``` {{EmbedLiveSample('Bad_Contrast', '100%', '100')}} ## Solution When choosing a color scheme for your website, choose foreground and background colors that have good contrast. Make the color contrast as good as it can be within your design constraints — ideally go for the AAA rating (see 1.4.6 below), but at least meet the AA rating (see 1.4.3 below). If you are including non-text content such as video or animation, you should follow 1.4.11 (again, see below). To check your contrast as you make your color choices, use a tool such as WebAIM's [Color Contrast Checker](https://webaim.org/resources/contrastchecker/). You can also check color contrast on the fly using Firefox's Developer Tools — see the [Accessibility inspector](https://firefox-source-docs.mozilla.org/devtools-user/accessibility_inspector/index.html) guide, and in particular the section [Check for accessibility issues](https://firefox-source-docs.mozilla.org/devtools-user/accessibility_inspector/index.html#check-for-accessibility-issues). Try using it on the live examples in the description section. ## Related WCAG success criteria - [1.4.3 Minimum contrast (AA)](https://www.w3.org/TR/WCAG21/#contrast-minimum) - : The color contrast between background and foreground content should be at a minimum level to ensure legibility: - Text and its background should have a contrast ratio of at least 4.5:1. - Heading (or just larger) text should have a ratio of at least 3:1. Larger text is defined as at least 18pt, or 14pt bold. - [1.4.6 Enhanced contrast (AAA)](https://www.w3.org/TR/WCAG21/#contrast-enhanced) - : This follows, and builds on, criterion 1.4.3. - Text and its background should have a contrast ratio of at least 7:1. - Heading (or just larger) text should have a ratio of at least 4.5:1. - [1.4.11 Non-Text Contrast (AA)](https://www.w3.org/TR/WCAG21/#non-text-contrast) (added in 2.1) - : There should be a minimum color contrast ratio of 3 to 1 for user interface components and graphical objects. ## See also - [Color and color contrast](/en-US/docs/Learn/Accessibility/CSS_and_JavaScript#color_and_color_contrast) - [Multiple labels](/en-US/docs/Learn/Forms/How_to_structure_a_web_form#multiple_labels) - [Understanding Non-Text Contrast](https://www.w3.org/WAI/WCAG21/Understanding/non-text-contrast.html)
0
data/mdn-content/files/en-us/web/accessibility/understanding_wcag/perceivable
data/mdn-content/files/en-us/web/accessibility/understanding_wcag/perceivable/use_of_color/index.md
--- title: Use of color slug: Web/Accessibility/Understanding_WCAG/Perceivable/Use_of_color page-type: guide --- {{QuicklinksWithSubPages("Web/Accessibility/Understanding_WCAG")}} While [color contrast](/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable/Color_contrast) is often primarily an aesthetic choice, the _use of color_ on a website pertains to _using color to communicate information_. WCAG guideline 1.4.1 on the use of color requires that "color is not used as the only visual means of conveying information, indicating an action, prompting a response, or distinguishing a visual element." ## Solution Use another factor in addition to color to convey information. For example, to indicate form validation errors, you can change the labels of the relevant fields by another font attribute as well as by color. Icons and symbols should differ by shape as well as by color. To accommodate users with color vision disorders ("color blindness"), be careful when using a "stoplight" color metaphor, with green indicating "good" values and red indicating "bad" values. Users with red-green color blindness have trouble distinguishing red and green, and so may not be able to tell these values apart. Using an additional factor to signal "good" vs. "bad" is necessary. Avoid pure red and green in this situation; a reddish-orange and a bluish-green are distinguishable by color blind users, while still conveying the cultural "good" and "bad" meanings to users with normal color vision. [Color contrast](/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable/Color_contrast) can be helpful in this context, as well, if one color is darker or lighter than the other. ## Related WCAG success criteria - [1.4.1 Use of color (A)](https://www.w3.org/TR/WCAG21/#use-of-color) - : Color is not used as the only visual means of conveying information, indicating an action, prompting a response, or distinguishing a visual element. ## See also - [Understanding Success Criterion 1.4.1: Use of Color](https://www.w3.org/WAI/WCAG21/Understanding/use-of-color.html) - [Color contrast](/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable/Color_contrast) - [Color and color contrast](/en-US/docs/Learn/Accessibility/CSS_and_JavaScript#color_and_color_contrast) in the Accessibility tutorials
0
data/mdn-content/files/en-us/web/accessibility/understanding_wcag
data/mdn-content/files/en-us/web/accessibility/understanding_wcag/keyboard/index.md
--- title: Keyboard slug: Web/Accessibility/Understanding_WCAG/Keyboard page-type: guide --- {{QuicklinksWithSubPages("Web/Accessibility/Understanding_WCAG")}} To be fully accessible, a web page must be operable by someone using only a keyboard to access and control it. This includes users of screen readers, but can also include users who have trouble operating a pointing device such as a mouse or trackball, or whose mouse is not working at the moment, or who prefer to use a keyboard for input whenever possible. ## Focusable elements should have interactive semantics If an element can be focused using the keyboard, then it should be interactive; that is, the user should be able to do something to it and produce a change of some kind (for example, activating a link or changing an option). > **Note:** One important exception to this rule is if the element has `role="document"` applied to it, **inside** an interactive context (such as `role="application"`). In such a case, focusing the nested document is the only way of returning assistive technology to a non-interactive state (often called "browse mode"). Most interactive elements are focusable by default; you can make an element focusable by adding a `tabindex=0` attribute value to it. However, you should only add `tabindex` if you have also made the element interactive, for example, by defining appropriate event handlers keyboard events. ### See also - [tabindex](/en-US/docs/Web/HTML/Global_attributes/tabindex) global HTML attribute - Element: [keydown event](/en-US/docs/Web/API/Element/keydown_event) - Element: [keyup event](/en-US/docs/Web/API/Element/keyup_event) ## Avoid using `tabindex` attribute greater than zero The `tabindex` attribute indicates that an element is focusable using the keyboard. A value of zero indicates that the element is part of the default focus order, which is based on the ordering of elements in the HTML document. A positive value puts the element ahead of those in the default ordering; elements with positive values are focused in the order of their `tabindex` values (1, then 2, then 3, etc.). This creates confusion for keyboard-only users when the focus order differs from the logical order of the page. A better strategy is to structure the HTML document so that focusable elements are in a logical order, without the need to re-order them with positive `tabindex` values. ### See also - [tabindex](/en-US/docs/Web/HTML/Global_attributes/tabindex) global HTML attribute - [Understanding focus order](https://www.w3.org/WAI/WCAG21/Understanding/focus-order.html) - [Don't use tabindex greater than 0](https://adrianroselli.com/2014/11/dont-use-tabindex-greater-than-0.html) ## Clickable elements must be focusable and should have interactive semantics If an element can be clicked with a pointing device, such as a mouse, then it should also be focusable using the keyboard, and the user should be able to do something by interacting with it. An element is clickable if it has an `onclick` event handler defined. You can make it focusable by adding a `tabindex=0` attribute value to it. You can make it operable with the keyboard by defining an `onkeydown` event handler; in most cases, the action taken by event handler should be the same for both types of events. ### See also - [tabindex](/en-US/docs/Web/HTML/Global_attributes/tabindex) global HTML attribute - Element: [keydown event](/en-US/docs/Web/API/Element/keydown_event) - Element: [keyup event](/en-US/docs/Web/API/Element/keyup_event) ## Interactive elements must be able to be activated using a keyboard If the user can interact with an element using touch or a pointing device, then the element should also support interacting using the keyboard. That is, if you have defined event handlers for touch or click events, you should also define them for keyboard events. The keyboard event handlers should enable the effectively the same interaction as the touch or click handlers. ### See also - Element: [keydown event](/en-US/docs/Web/API/Element/keydown_event) - Element: [keyup event](/en-US/docs/Web/API/Element/keyup_event) ## Interactive elements must be focusable If the user can interact with an element (for example, using touch or a pointing device), then it should be focusable using the keyboard. You can make it focusable by adding a `tabindex=0` attribute value to it. That will add the element to the list of elements that can be focused by pressing the <kbd>Tab</kbd> key, in the sequence of such elements as defined in the HTML document. ### See also - [tabindex](/en-US/docs/Web/HTML/Global_attributes/tabindex) global HTML attribute ## Focusable element must have focus styling Any element that can receive keyboard focus should have visible styling that indicates when the element is focused. You can do this with the [`:focus`](/en-US/docs/Web/CSS/:focus) and [`:focus-visible`](/en-US/docs/Web/CSS/:focus-visible) CSS pseudo-classes. Standard focusable elements such as links and input fields are given special styling by the browser by default, so you might not need to specify focus styling for such elements, unless you want the focus styling to be more distinctive. If you create your own focusable components, be sure that you also define focus styling for them. ### See also - [Using CSS to change the presentation of a UI component when it receives focus](https://www.w3.org/WAI/WCAG21/Techniques/css/C15.html)
0
data/mdn-content/files/en-us/web/accessibility/understanding_wcag
data/mdn-content/files/en-us/web/accessibility/understanding_wcag/operable/index.md
--- title: Operable slug: Web/Accessibility/Understanding_WCAG/Operable page-type: guide --- {{QuicklinksWithSubPages("Web/Accessibility/Understanding_WCAG")}} This article provides practical advice on how to write your web content so that it conforms to the success criteria outlined in the **Operable** principle of the Web Content Accessibility Guidelines (WCAG) 2.0 and 2.1. Operable states that user interface components and navigation must be operable. > **Note:** To read the W3C definitions for Operable and its guidelines and success criteria, see [Principle 2: Operable — User interface components and navigation must be operable.](https://www.w3.org/TR/WCAG21/#operable) ## Guideline 2.1 — Keyboard Accessible: Make all functionality available from a keyboard This guideline covers the necessity of making core website functionality available via a keyboard in addition to other means (e.g. mouse), so that users that rely on keyboard controls can access them. <table class="standard-table"> <thead> <tr> <th scope="col">Success criteria</th> <th scope="col">How to conform to the criteria</th> <th scope="col">Practical resource</th> </tr> </thead> <tbody> <tr> <td>2.1.1 Keyboard (A)</td> <td> All functionality should be accessible using keyboard controls, unless it cannot be done using the keyboard (e.g. freehand drawing). Built-in controls should be used where possible (e.g. tabbing through form controls), and you should only build in custom functionality where needed. </td> <td> See <a href="/en-US/docs/Learn/Accessibility/HTML#ui_controls" >UI controls</a > and <a href="/en-US/docs/Learn/Accessibility/HTML#building_keyboard_accessibility_back_in" >Building keyboard accessibility back in</a > </td> </tr> <tr> <td>2.1.2 No keyboard trap (A)</td> <td> <p> When entering a section of functionality using the keyboard, you should be able to get out of that section again using *only* the keyboard. For example, if you press <kbd>Enter</kbd>/<kbd>Return</kbd> on a focused button to open an options window, you should be able to close that window again and return to the main content using the keyboard. </p> <p> This is very important so that keyboard users do not get trapped on specific sections of your apps. </p> </td> <td></td> </tr> <tr> <td>2.1.3 Keyboard — all functionality (AAA)</td> <td> This is a further step beyond criterion 2.1.1. To achieve AAA conformance, all functionality should be accessible using keyboard controls — with no exceptions. </td> <td> See <a href="/en-US/docs/Learn/Accessibility/HTML#ui_controls" >UI controls</a > and <a href="/en-US/docs/Learn/Accessibility/HTML#building_keyboard_accessibility_back_in" >Building keyboard accessibility back in</a > </td> </tr> <tr> <td> 2.1.4 Character Key Shortcuts (A) <em ><a href="https://www.w3.org/TR/WCAG21/#new-features-in-wcag-2-1" >added in 2.1</a ></em > </td> <td> If a single character key shortcut exists, then at least one of the following is true: single character key shortcuts can be turned off, remapped or are only active when the relevant user interface component is in focus. </td> <td> <a href="https://www.w3.org/WAI/WCAG21/Understanding/character-key-shortcuts.html" >Understanding Character Key Shortcuts</a > </td> </tr> </tbody> </table> > **Note:** Also see the WCAG description for [Guideline 2.1 Keyboard Accessible: Make all functionality available from a keyboard](https://www.w3.org/TR/WCAG21/#keyboard-accessible). ## Guideline 2.2 — Enough Time: Provide users enough time to read and use content This guideline covers situations in which functionality may have a time limit. For example, purchases sometimes need to be completed within a time limit for security reasons. <table class="standard-table"> <thead> <tr> <th scope="col">Success criteria</th> <th scope="col">How to conform to the criteria</th> <th scope="col">Practical resource</th> </tr> </thead> <tbody> <tr> <td>2.2.1 Timing is adjustable (A)</td> <td> <p> For functionality with time limits (e.g. completing a hotel or flight booking often has a time limit), the user should be given controls to allow them to adjust, extend or turn off the time limit. </p> <p> Exceptions to this are activities with time limits longer than 20 hours, real time events (e.g. live multiplayer games), and any other activity that requires a time limit and would be invalidated if it were turned off. </p> </td> <td></td> </tr> <tr> <td>2.2.2 Pausing, stopping, hiding (A)</td> <td> <p> For moving/blinking content that starts automatically, lasts longer than 5 seconds, and is shown alongside other content, controls should be provided to pause, stop, or hide it. This does not apply to moving/blinking content that is essential to the experience. Examples include scrolling text and videos. </p> <p> For auto-updating information that starts automatically and is shown alongside other content, controls should be provided to pause, stop, or hide it, or to control the frequency of updates. This does not apply to auto-updating content that is essential to the experience. Examples include carousels or rotating announcements. </p> </td> <td></td> </tr> <tr> <td>2.2.3 No time limits (AAA)</td> <td> This builds on criteria 2.2.1, stating that content that wants to pass AAA conformance should have no time limits. </td> <td></td> </tr> <tr> <td>2.2.4 Suppress interruptions (AAA)</td> <td> Any interruptions such as alerts or interstitial adverts should have functionality available to suppress or postpone them, unless it is an emergency alert. </td> <td></td> </tr> <tr> <td>2.2.5 Re-authenticating (AAA)</td> <td> If an authentication session expires during usage of a web app, the user can re-authenticate and continue their usage without losing any data. </td> <td></td> </tr> <tr> <td> 2.2.6 Timeouts (AAA) <em ><a href="https://www.w3.org/TR/WCAG21/#new-features-in-wcag-2-1" >added in 2.1</a ></em > </td> <td> <p> If there is a timeout (caused by user inactivity) warn users at the start of a process so they will not be surprised that a timeout exists (or only allow the timeout to occur after 20 hours of inactivity). </p> </td> <td> <a href="https://www.w3.org/WAI/WCAG21/Understanding/timeouts.html" >Understanding Timeouts</a > </td> </tr> </tbody> </table> > **Note:** Also see the WCAG description for [Guideline 2.2 Enough Time: Provide users enough time to read and use content](https://www.w3.org/TR/WCAG21/#enough-time). ## Guideline 2.3 — Seizures and Physical Reactions: Do not design content in a way that is known to cause seizures or physical reactions This refers to content that, if not changed, could cause seizures in users with conditions such as epilepsy OR could cause physical reactions (like dizziness) for users with conditions such as vestibular disorders. <table> <thead> <tr> <th scope="col">Success criteria</th> <th scope="col">How to conform to the criteria</th> <th scope="col">Practical resource</th> </tr> </thead> <tbody> <tr> <td>2.3.1 Three flashes, or below threshold (A)</td> <td>Content doesn't contain any aspect that Flashes more than three times per second, or flashing content is below acceptable <a href="https://www.w3.org/TR/WCAG20/#general-thresholddef">flash and red flash thresholds</a>.</td> <td></td> </tr> <tr> <td>2.3.2 Three flashes (AAA)</td> <td>Content doesn't contain any aspect that Flashes more than three times per second.</td> <td></td> </tr> <tr> <td>2.3.3 Animations from Interactions (AAA) <em><a href="https://www.w3.org/TR/WCAG21/#new-features-in-wcag-2-1">added in 2.1</a></em></td> <td>Allow users to disable animations from interactions (unless the animation is essential).</td> <td><a href="https://www.w3.org/TR/WCAG21/#animation-from-interactions">Understanding Animations from Interactions</a></td> </tr> </tbody> </table> > **Note:** Also see the WCAG description for [Guideline 2.3 Seizures and Physical Reactions: Do not design content in a way that is known to cause seizures or physical reactions.](https://www.w3.org/TR/WCAG21/#seizures-and-physical-reactions) ## Guideline 2.4 — Navigable: Provide ways to help users navigate, find content, and determine where they are The conformance criteria under this guideline relate to ways in which users can be expected to orientate themselves, and find the content and functionality they are looking for on the current page or other pages of the site. <table class="standard-table"> <thead> <tr> <th scope="col">Success criteria</th> <th scope="col">How to conform to the criteria</th> <th scope="col">Practical resource</th> </tr> </thead> <tbody> <tr> <td>2.4.1 Bypass blocks (A)</td> <td> <p> A mechanism should be provided that allows the user to skip straight to the main content or functionality available on the page, past the repeated features (such as the company logo or navigation). This is often achieved using "skip links" — links put at the top of the page source that link to the main content and are hidden by CSS. </p> <p> If a proper structure of headings and semantic containers is provided to navigate with (for example {{htmlelement("section")}}, {{htmlelement("aside")}}, etc.), then an added "skip link" is not needed. </p> </td> <td><em>Need to add a section on "skip links".</em></td> </tr> <tr> <td>2.4.2 Include page title (A)</td> <td> Each web page should include an informative {{htmlelement("title")}}, the content of which describes the page's content/purpose. </td> <td> See <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML#adding_a_title" >Adding a title</a >. </td> </tr> <tr> <td>2.4.3 Logical focus order (A)</td> <td> The "tabbing order" of focusable page features (e.g. links, buttons, form inputs) makes logical sense, meaning that the page is still usable by non-sighted/keyboard users. </td> <td> See <a href="/en-US/docs/Learn/Accessibility/HTML#ui_controls" >UI controls</a > for general advice on tabbing to controls. If you need to place elements in an unusual layout, it is better to make sure the source order is sensible, then use CSS features like <a href="/en-US/docs/Learn/CSS/CSS_layout/Positioning">positioning</a> to handle the layout. </td> </tr> <tr> <td>2.4.4 Link purpose (in context) (A)</td> <td> The purpose/destination of a link can be determined from the link text, or from its surroundings (e.g. the surrounding text). Exceptions are where the link purpose is ambiguous to <em>all</em> users (see <a href="https://www.w3.org/TR/WCAG20/#ambiguouslinkdef" >ambiguous to users in general</a > for a useful explanation of this). </td> <td> See <a href="/en-US/docs/Learn/Accessibility/HTML#meaningful_text_labels" >Meaningful text labels</a >. Also note that you should minimize instances where multiple copies of the same text are linked to different places. This can cause problems for screen reader users, who will often bring up a list of the links out of context — several links all labelled "click here", "click here", "click here" would be confusing. </td> </tr> <tr> <td>2.4.5 Multiple navigation mechanisms (AA)</td> <td> <p> You should provide at least two general navigation mechanisms to find pages on your website, for example navigation menu, breadcrumb trail, site search, site map, list of related links, etc. </p> <p> The only exception to this is where a page is one step in a process, so should only logically have links to the previous and next steps. </p> </td> <td> Most of these mechanisms can be created using simple HTML features, for example see <a href="/en-US/docs/Learn/Forms/Basic_native_form_controls#search_field" >Search field</a >, <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML/Creating_hyperlinks#active_learning_creating_a_navigation_menu" >Creating a navigation menu</a >, <a href="/en-US/docs/Learn/CSS/Styling_text/Styling_links#styling_links_as_buttons" >Styling links as buttons</a >. </td> </tr> <tr> <td>2.4.6 Headings and labels (AA)</td> <td> Heading (e.g. {{htmlelement("Heading_Elements", "&lt;h2&gt;")}}) and {{htmlelement("label")}} elements clearly describe the purpose of the content and form elements they are supposed to be describing. </td> <td> <p> See <a href="/en-US/docs/Learn/Accessibility/HTML#ui_controls" >UI controls</a >, <a href="/en-US/docs/Learn/Accessibility/HTML#meaningful_text_labels" >Meaningful text labels</a >, <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals#the_basics_headings_and_paragraphs" >The basics of headings and paragraphs</a >, <a href="/en-US/docs/Learn/Forms/How_to_structure_a_web_form#the_%3clabel%3e_element" >The &#x3C;label> element</a >. </p> <p> Note that you should avoid duplicating headings or labels (e.g. multiple instances of "Further information"), unless the structure allows you to differentiate between them easily. </p> </td> </tr> <tr> <td>2.4.7 Visible focus for focusable elements (AA)</td> <td> When tabbing through focusable elements such as links or form inputs, there should be a visual indicator to show you which element currently has focus. This is usually a dotted or blue outline by default (depending on browser, platform, etc.), but this can be overridden by CSS. </td> <td> See <a href="/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility#using_native_keyboard_accessibility" >Using native keyboard accessibility</a >. </td> </tr> <tr> <td>2.4.8 Location within site (AAA)</td> <td> When on a page inside a complex site or set of steps, the user should be given an indicator of where they are in the site, for example a breadcrumb trail, sitemap or text such as "Form page 2 of 10". </td> <td></td> </tr> <tr> <td>2.4.9 Link purpose (link only) (AAA)</td> <td> This criterion builds on 2.4.4, stating that to conform to AAA, the purpose/destination of a link should be determinable from the link text alone, even if out of context. </td> <td> See <a href="/en-US/docs/Learn/Accessibility/HTML#meaningful_text_labels" >Meaningful text labels</a >. Also note that you should minimize instances where multiple copies of the same text are linked to different places. This can cause problems for screen reader users, who will often bring up a list of the links out of context — several links all labelled "click here", "click here", "click here" would be confusing. </td> </tr> <tr> <td>2.4.10 Section headings (AAA)</td> <td> <p> As well as creating a useful document structure, headings should also accurately describe and break up content areas into logical sections. </p> <p> Note that this criterion refers to headings and titles in general web content (e.g. headings within text content). Headings and titles for user interfaces are a special case covered in criterion 4.1.2. </p> </td> <td> <p> See <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals#the_basics_headings_and_paragraphs" >The basics of headings and paragraphs</a >. </p> </td> </tr> <tr> <td> 2.4.11 Focus not obscured (Minimum) (AA)</td> <td> <p> When a user interface component receives keyboard focus, the component is not entirely hidden due to containing author-created content.</p> <p> <strong>Note:</strong> If the interface's content can be repositioned by the user, then only the initial position of the user-movable content is considered for testing to conform to this standard. Also, content opened by the user may obscure the component receiving focus. Furthermore, if the user can reveal the focused component without changing keyboard focus, the component with focus is not considered hidden for conformance and testing purposes.</p> </td> <td> <p> Check out <a href="https://www.w3.org/WAI/WCAG22/Understanding/focus-not-obscured-minimum">Understanding focus not obscured (Minimum)</a> to learn more about this standard.</p> </td> </tr> <tr> <td> 2.4.12 Focus not obscured (Enhanced) (AAA) </td> <td> <p> Follows the rules as 2.4.11 except when a user interface component receives focus, no part of the component can be hidden by author-created content. If the interface is configurable, only the initial positions of user-movable content are considered for testing and meeting of this standard.</p> </td> <td> <p> Check out <a href="https://www.w3.org/WAI/WCAG22/Understanding/focus-not-obscured-enhanced">Understanding focus not obscured (Enhanced) (Level AAA)</a> to learn more about this standard.</p> </td> </td> </tr> <tr> <td> 2.4.13 Focus appearance (AAA)</td> <td> <p>When the keyboard focus indicator is visible, the area of the focus indicator meets all the following:</p> <ul> <li>Must be at least as large as the area of a <code>2px</code> thick perimeter of the unfocused component or sub-component, which includes component's content, border, and background, excluding outer shadows or glow effects.</li> <li>Needs to have a contrast ratio of at least 3:1 between the same pixels in the focused and unfocused states</li> </ul> <p> The exceptions to this are:</p> <ul> <li>The focus indicator is determined by the user and cannot be adjusted by the author.</li> <li>The focus indicator and the indicator's background color are not modified by the author.</li> </ul> </td> <td> <p> Check out <a href="https://www.w3.org/WAI/WCAG22/Understanding/focus-appearance.html">Understanding focus appearance (Level AAA)</a> to learn more about this standard.</p> </td> </tr> </tbody> </table> > **Note:** Also see the WCAG description for [Guideline 2.4 Navigable: Provide ways to help users navigate, find content, and determine where they are.](https://www.w3.org/TR/WCAG21/#navigable) ## Guideline 2.5 Input Modalities: Make it easier for users to operate functionality through various inputs beyond keyboard The conformance criteria under this guideline ensures that users are able to interact with digital technology using different input methods beyond a keyboard or mouse (including touchscreen, voice, device motion, or alternative input devices). <table> <thead> <tr> <th scope="col">Success criteria</th> <th scope="col">How to conform to the criteria</th> <th scope="col">Practical resource</th> </tr> </thead> <tbody> <tr> <td>2.5.1 Pointer Gestures (A) <em><a href="https://www.w3.org/TR/WCAG21/#new-features-in-wcag-2-1">added in 2.1</a></em></td> <td>All functionality that can be operated with a pointer can be operated with single-point actions. Path-based or multi-point gestures are not required to operate any functionality. Exceptions exist.</td> <td><a href="https://www.w3.org/WAI/WCAG21/Understanding/pointer-gestures.html">Understanding Pointer Gestures</a></td> </tr> <tr> <td>2.5.2 Pointer Cancellation (A) <em><a href="https://www.w3.org/TR/WCAG21/#new-features-in-wcag-2-1">added in 2.1</a></em></td> <td>For functionality that can be operated using a single-pointer at least one of the following is true: no down-event, abort/undo, up reversal or essential.</td> <td><a href="https://www.w3.org/WAI/WCAG21/Understanding/pointer-cancellation.html">Understanding Pointer Cancellation</a></td> </tr> <tr> <td>2.5.3 Label in Name (A) <em><a href="https://www.w3.org/TR/WCAG21/#new-features-in-wcag-2-1">added in 2.1</a></em></td> <td>For each user interface component that includes a visible text label, make sure the accessible name matches (or includes) the visible text in the label.</td> <td><a href="https://www.w3.org/WAI/WCAG21/Understanding/label-in-name.html">Understanding Label in Name</a></td> </tr> <tr> <td>2.5.4 Motion Actuation (A) <em><a href="https://www.w3.org/TR/WCAG21/#new-features-in-wcag-2-1">added in 2.1</a></em></td> <td>Ensure that for functionality that can be triggered by a) device motion (like shaking, tilting) or b) user gestures detected by device sensors (including a camera) that both of the following are true: 1) motion actuation can be disabled, and 2) the functionality can be operated without using device motion or user gestures. Exceptions exist.</td> <td><a href="https://www.w3.org/WAI/WCAG21/Understanding/motion-actuation.html">Understanding Motion Actuation</a></td> </tr> <tr> <td>2.5.5 Target Size (AAA) <em><a href="https://www.w3.org/TR/WCAG21/#new-features-in-wcag-2-1">added in 2.1</a></em></td> <td>The size of an actionable item's touch target must be at least 44 CSS pixels in both width and height. Exceptions exist.</td> <td><a href="https://www.w3.org/WAI/WCAG21/Understanding/target-size.html">Understanding Target Size</a></td> </tr> <tr> <td>2.5.6 Concurrent Input Mechanisms (AAA) <em><a href="https://www.w3.org/TR/WCAG21/#new-features-in-wcag-2-1">added in 2.1</a></em></td> <td>Make sure people can use and switch between different modes of input when interacting with digital content including touchscreen, keyboard, mouse, voice commands, or alternative input devices. An essential exception exists. </td> <td><a href="https://www.w3.org/WAI/WCAG21/Understanding/concurrent-input-mechanisms.html">Understanding Concurrent Input Mechanism</a></td> </tr> <tr> <td> 2.5.8 Target size minimum (AA)</td> <td> Target size for pointer inputs should be at least `24px` wide by `24px` tall except for the following areas: <ul> <li> <strong>Spacing:</strong>Targets that are less than `24px x 24px` are positioned so that if a `24px` diameter circle is centered on each target's bounding box, the circles do not intersect with any other target or the circle for another undersized target.</li> <li> <strong>Equivalent:</strong> A separate control that achieves the same function that meets this standard is available on the same page.</li> <li> <strong>Inline:</strong> The target is located within a line of text with its size constrained by the line height or surrounding non-target text.</li> <li> <strong>User agent control:</strong> The target's size is determined by the user agent and has not been modified by the author.</li> <li> <strong>Essential:</strong> A particular presentation of the target is essential or legally required for the information being conveyed.</li> </ul> <td> Check out <a href="https://www.w3.org/WAI/WCAG22/Understanding/target-size-minimum.html">Understanding target size minimum</a> </td> </tr> </tr> </tbody> </table> > **Note:** Also see the WCAG description for [Guideline 2.5: Input Modalities: Make it easier for users to operate functionality through various inputs beyond keyboard.](https://www.w3.org/TR/WCAG21/#input-modalities) ## See also - [WCAG](/en-US/docs/Web/Accessibility/Understanding_WCAG) 1. [Perceivable](/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable) 2. Operable 3. [Understandable](/en-US/docs/Web/Accessibility/Understanding_WCAG/Understandable) 4. [Robust](/en-US/docs/Web/Accessibility/Understanding_WCAG/Robust)
0
data/mdn-content/files/en-us/web/accessibility/understanding_wcag
data/mdn-content/files/en-us/web/accessibility/understanding_wcag/text_labels_and_names/index.md
--- title: Text labels and names slug: Web/Accessibility/Understanding_WCAG/Text_labels_and_names page-type: guide --- {{QuicklinksWithSubPages("Web/Accessibility/Understanding_WCAG")}} There are many situations in which a control, dialog, or other website feature should be given a descriptive name or label to allow users of assistive technologies to understand what its purpose is and how to operate it correctly. There are a number of different types of problems in this category, found in different contexts, and each has its own solution. The different problems and solutions are discussed in the sections below. ## Use alt attribute to label area elements that have the href attribute In image maps, give each {{htmlelement("area")}} element an `alt` attribute containing a name that describes what resources the areas links to. Failure to do so makes an image map hard to use for users of assistive technology — they need alternative text to be able to understand the purpose of an image. ### Examples The following example show a simple image map (taken from [H24: Providing text alternatives for the area elements of image maps](https://www.w3.org/TR/WCAG20-TECHS/H24.html)): ```html <img src="welcome.gif" usemap="#map1" alt="Areas in the library. Select an area for more information on that area." /> <map id="map1" name="map1"> <area shape="rect" coords="0,0,30,30" href="reference.html" alt="Reference" /> <area shape="rect" coords="34,34,100,100" href="media.html" alt="Audio visual lab" /> </map> ``` See the [`<area>` element reference page](/en-US/docs/Web/HTML/Element/area) for a live interactive example. ### See also - {{htmlelement("area")}} - [H24: Providing text alternatives for the area elements of image maps](https://www.w3.org/TR/WCAG20-TECHS/H24.html) ## Dialogs should be labeled For any container whose contents act as a dialog box (for example, a modal dialog asking the user to make a choice or respond to an action being taken), give it a descriptive label or name, so that assistive technology users can easily discover what its purpose is. A dialog box is generally denoted by an ARIA [`role="dialog"`](/en-US/docs/Web/Accessibility/ARIA/Roles/dialog_role) or [`role="alertdialog"`](/en-US/docs/Web/Accessibility/ARIA/Roles/alertdialog_role); you can use the [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) or [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) attributes to provide a label. ### Examples The following example shows a simple dialog box, defined as such using `role="dialog"` and labelled using `aria-labelledby`. ```html <div role="dialog" aria-labelledby="dialog1Title" aria-describedby="dialog1Desc"> <h2 id="dialog1Title">Your personal details were successfully updated</h2> <p id="dialog1Desc"> You can change your details at any time in the user account section. </p> <button>Close</button> </div> ``` If the dialog box doesn't have a heading, you can instead use `aria-label` to contain the label text: ```html <div role="dialog" aria-label="Personal details updated confirmation"> <p> Your personal details were successfully updated. You can change your details at any time in the user account section. </p> <button>Close</button> </div> ``` ### See also - [`role="dialog"`](/en-US/docs/Web/Accessibility/ARIA/Roles/dialog_role) - [`role="alertdialog"`](/en-US/docs/Web/Accessibility/ARIA/Roles/alertdialog_role) - [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) - [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) - [WAI-ARIA: dialog role](https://www.w3.org/TR/wai-aria-1.2/#dialog) - [Dialog authoring practices](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/) ## Documents must have a title It is important in each HTML document to include a {{htmlelement("title")}} that describes the page's purpose. A common navigation technique for users of assistive technology is to infer what content a page contains by reading its title. If the title is not available, they have to navigate the page to determine its content, which can be a time consuming and potentially confusing process. ### Examples The title for the reference article about the {{htmlelement("title")}} element is as follows: ```html <title> &lt;title&gt;: The Document Title element - HTML: Hypertext Markup Language | MDN </title> ``` Another example might look like so: ```html <title>Fill in your details to register — myGov services</title> ``` To help the user, you can update the page title value to reflect significant page state changes (such as form validation problems): ```html <title>2 errors — Fill in your details to register — myGov services</title> ``` ### See also - {{htmlelement("title")}} ## Embedded content must be labeled Make sure that elements that embed content have a [title](/en-US/docs/Web/HTML/Global_attributes/title) attribute that describes the embedded content. This includes the {{htmlelement("embed")}} and {{htmlelement("object")}} elements. These elements are often used for graphical content, much like the {{HTMLelement("img")}} element. A descriptive title helps users of assistive technology understand what the element is showing. ## Figures with optional captions should be labeled For best accessibility, include a {{HTMLElement("figcaption")}} within a {{HTMLElement("figure")}} element, even though doing so is technically optional. The caption is in addition to any alternative text on images within the figure. The caption describes the purpose of the figure in the document, which may be different from a simple description of a visual item, as provided by the alternative text. ### Example The following example shows code for a figure with a caption. The `alt` attribute of the {{htmlelement("img")}} describes the appearance of the image; the {{htmlelement("figcaption")}} describes it from a functional perspective (in this case, the Latin name of the flower in the image). ```html <figure> <img src="milkweed.jpg" alt="Black and white close-up photo of milkweed flowers" /> <figcaption>Asclepias verticillata</figcaption> </figure> ``` ## Fieldset elements must be labeled Fieldset elements must have a text description, similar to other form elements. Use the {{htmlelement("legend")}} element to describe the purpose of a fieldset. ## Use a legend to label a fieldset When grouping a set of form elements together with a {{htmlelement("fieldset")}} element, you should include a nested {{htmlelement("legend")}} element inside it, containing a clear description of the group. Users of assistive technology find this description helpful when trying to work out the overall purpose of the group. Without the legend, they would have to navigate around the individual form controls in the group to infer an idea of the overall purpose, which could result in confusion. ### Examples ```html <form> <fieldset> <legend>Choose your favorite monster</legend> <input type="radio" id="kraken" name="monster" value="K" /> <label for="kraken">Kraken</label><br /> <input type="radio" id="sasquatch" name="monster" value="S" /> <label for="sasquatch">Sasquatch</label><br /> <input type="radio" id="mothman" name="monster" value="M" /> <label for="mothman">Mothman</label> </fieldset> </form> ``` You can see a live, interactive version of this example on the [`<fieldset>` reference page](/en-US/docs/Web/HTML/Element/fieldset). ### See also - {{htmlelement("fieldset")}} - {{htmlelement("legend")}} ## Form elements must be labeled All elements within a form must have a {{htmlelement("label")}} that identifies its purpose. This applies to all types of {{htmlelement("input")}} items, as well as {{htmlelement("button")}}, {{htmlelement("output")}}, {{htmlelement("select")}}, {{htmlelement("textarea")}}, {{htmlelement("progress")}} and {{htmlelement("meter")}} elements, as well as any element with the [`switch` ARIA role](/en-US/docs/Web/Accessibility/ARIA/Roles/switch_role). The form element can be placed inside the {{htmlelement("label")}}, in which case the association between the form element and the label is obvious from the structure. Or, you can create an association between a {{htmlelement("label")}} and a form element by specifying the form element's `id` value as the value of the label's `for` attribute. ### Example ```html <label >I agree to the terms and conditions. <input type="checkbox" id="terms" name="terms" /> </label> <input type="checkbox" id="emailoptin" name="optin" /> <label for="emailoptin">Yes, please send me news about this product.</label> ``` ## Form elements should have a visible text label In addition to having a {{htmlelement("label")}} for every form element, those labels should be visible, not hidden. Visible labels help _all_ users understand the purpose of a form element. Do not rely on placeholder text, because it disappears as soon as the user starts typing. ## Frame elements must be labeled Frame elements, both {{htmlelement("iframe")}} and the older, obsolete {{htmlelement("frame")}}, must have a title to describe the contents of the frame. Use the `title` attribute to label a frame element. Without a title, users of assistive technologies have to navigate into the frame in order to understand what it contains, which can be difficult and confusing. The {{HTMLElement('frame')}} element is no longer part of the HTML specification. Support for it may be dropped by browsers in the future. In addition, it is difficult for screen readers to navigate pages with {{HTMLElement('frame')}} elements. For best accessibility and future maintenance, redesign any pages that use frames to use CSS to achieve a similar layout. As a best practice, also provide a {{htmlelement("title")}} for the document that is enclosed in the frame, with content identical to the frame's `title` attribute. (This assumes that the enclosed document is under your control; if not, try to match the frame's `title` attribute to the document's title.) Some screen readers replace the contents of the `title` attribute with the contents of the enclosed document's {{htmlelement("title")}}. It's safest and most accessible to provide the same title in both places. ### Example ```html <iframe title="MDN Web docs" width="300" height="200" src="https://developer.mozilla.org"> </iframe> ``` ## Headings must be labeled Make sure that your headings have non-empty text content, and are not hidden, such as with CSS `display:none` or `aria-hidden=true`. Users of screen readers rely on headings to understand the structure and content of a document. Also, be sure you are using [heading elements](/en-US/docs/Web/HTML/Element/Heading_Elements) only for actual section headings, and not as a shortcut way to make text stand out. Screen reader users typically "skim" a page's headings, much like sighted users; non-heading text that is marked-up with heading elements can cause confusion. ## Headings should have visible text content Make sure that your headings have non-empty text content, and are not hidden, such as with CSS `display:none` or `aria-hidden=true`. Users of screen readers rely on headings to understand the structure and content of a document. Do not use heading elements to mark up images or other graphical content. ## Use title attribute to describe `<iframe>` content Make sure that {{htmlelement("iframe")}} elements have a `title` attribute to describe the contents of the frame. Without a title, users of assistive technologies have to navigate into the frame in order to understand what it contains, which can be difficult and confusing. As a best practice, also provide a {{htmlelement("title")}} for the document that is enclosed in the frame, with content identical to the frame's `title` attribute. (This assumes that the enclosed document is under your control; if not, try to match the frame's `title` attribute to the document's title.) Some screen readers replace the contents of the `title` attribute with the contents of the enclosed document's {{htmlelement("title")}}. It's safest and most accessible to provide the same title in both places. ## Content with images must be labeled Provide descriptive text for all contentful (that is, non-decorative) images and image-like elements. This includes SVG images, {{htmlelement("img")}}, {{htmlelement("canvas")}}, {{htmlelement("map")}}, and {{htmlelement("area")}} elements, as well as {{htmlelement("input")}} elements where `type=image` and {{htmlelement("object")}} elements where the `type` starts with `image/`. The typical way to do this is with the `alt` attribute. Be sure that the description conveys what is shown in the image. ### Example ```html <img src="milkweed.jgp" alt="Black and white close-up photo of milkweed flowers" /> ``` ## Interactive elements must be labeled If an element is intended for users to interact with it, it should have a label. Interactive elements include links ({{htmlelement("a")}}), form elements, buttons, and any element that has a handler for mouse or keyboard events. The way to label an element depends on its type: for form elements, use a {{htmlelement("label")}}; for links, buttons and clickable elements, the text content of the element typically provides the label. If no other option exists for labeling an element, use the [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) attribute. ## Use label attribute on optgroup elements In an {{htmlelement("optgroup")}} element, use the `label` attribute to describe the group so that assistive technologies can access it for their users. ### Example In this example, the `label` attribute on the {{HTMLElement('optgroup')}} elements gives a category name for the group of options. ```html <label for="dino-select">Choose a dinosaur:</label> <select id="dino-select"> <optgroup label="Theropods"> <option>Tyrannosaurus</option> <option>Velociraptor</option> <option>Deinonychus</option> </optgroup> <optgroup label="Sauropods"> <option>Diplodocus</option> <option>Saltasaurus</option> <option>Apatosaurus</option> </optgroup> </select> ``` ## Toolbars must be labeled when there is more than one toolbar If you define more than one toolbar in a web application using the ARIA `toolbar` role, you must use the [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) attribute to label each one so that it can be described by assistive technology. It is a good practice to label a toolbar, even if there is only one per page. ### See also - [W3C ARIA toolbar example](https://www.w3.org/WAI/ARIA/apg/patterns/toolbar/examples/toolbar/) ## Related WCAG success criteria - [1.1.1 Non-text Content (A)](https://www.w3.org/TR/WCAG21/#non-text-content) - : All non-text content that is presented to the user has a text alternative that serves the equivalent purpose, except for the situations listed in the above link. - [2.4.4 Link Purpose (In Context) (A)](https://www.w3.org/TR/WCAG21/#link-purpose-in-context) - : The purpose of each link can be determined from the link text alone or from the link text together with its programmatically determined link context, except where the purpose of the link would be ambiguous to users in general. - [2.4.9 Link Purpose (Link Only) (AAA)](https://www.w3.org/TR/WCAG21/#link-purpose-link-only) - : A mechanism is available to allow the purpose of each link to be identified from link text alone, except where the purpose of the link would be ambiguous to users in general.
0
data/mdn-content/files/en-us/web/accessibility
data/mdn-content/files/en-us/web/accessibility/mobile_accessibility_checklist/index.md
--- title: Mobile accessibility checklist slug: Web/Accessibility/Mobile_accessibility_checklist page-type: guide --- <section id="Quick_links"> {{ListSubpagesForSidebar("Web/Accessibility", 1)}} </section> This document provides a concise checklist of accessibility requirements for mobile app developers. It is intended to continuously evolve as more patterns arise. ## Color - Color contrast must comply with [WCAG 2.1 AA level requirements](https://www.w3.org/TR/WCAG/#contrast-minimum): - Contrast ratio of 4.5:1 for normal text (less than 18 point or 14 point bold.) - Contrast ratio of 3:1 for large text (at least 18 point or 14 point bold.) - Information conveyed via color must be also available by other means too (underlined text for links, etc.) ## Visibility - Content hiding techniques such as zero opacity, z-index order and off-screen placement must not be used exclusively to handle visibility. - Everything other than the currently visible screen must be _truly_ invisible (especially relevant for single page apps with multiple _cards_): - Use the `hidden` attribute or `visibility` or `display` style properties. - Unless absolutely unavoidable, `aria-hidden` attribute should not be used. ## Focus - All activatable elements must be focusable: - Standard controls such as links, buttons, and form fields are focusable by default. - Non-standard controls must have an appropriate [ARIA Role](/en-US/docs/Web/Accessibility/ARIA/Roles) assigned to them, such as `button`, `link`, or `checkbox`. - Focus should be handled in a logical order and consistent manner. ## Text equivalents - Text equivalent must be provided for every non-strictly presentational non-text element within the app. - Use _alt_ and _title_ where appropriate (read Steve Faulkner's post about [Using the HTML title attribute](https://www.tpgi.com/using-the-html-title-attribute-updated/) for a good guide.) - If the above attributes are not applicable, use appropriate [ARIA States and Properties](https://www.w3.org/TR/wai-aria-1.1/#state_prop_def) such as `aria-label`, `aria-labelledby`, or `aria-describedby`. - Images of text must be avoided. - All user interface components with visible text (or image of text) as labels must have the same text available in the programmatic [name](https://www.w3.org/TR/WCAG21/#dfn-name) of the component. [WCAG 2.1: Label in name.](https://www.w3.org/WAI/WCAG21/Understanding/label-in-name.html) - All form controls must have labels ({{ htmlelement("label") }} elements) for the benefit of screen reader users. ## Handling state - Standard controls such as radio buttons and checkboxes are handled by the operating system. However, for other custom controls state changes must be provided via [ARIA States](https://www.w3.org/TR/wai-aria-1.1/#state_prop_def) such as `aria-checked`, `aria-disabled`, `aria-selected`, `aria-expanded`, and `aria-pressed`. ## Orientation - Content should not be restricted to a single orientation, such as portrait or landscape, unless essential. [WCAG 2.1: Orientation](https://www.w3.org/WAI/WCAG21/Understanding/orientation.html) - Examples of when an orientation is essential is a piano application or a bank check. ## General guidelines - An app title must be provided. - Headings must not break hierarchical structure ```html <h1>Top level heading</h1> <h2>Secondary heading</h2> <h2>Another secondary heading</h2> <h3>Low level heading</h3> ``` - [ARIA Landmark Roles](https://www.washington.edu/accessibility/websites/regions/) should be used to describe an app or document structure, such as `banner`, `complementary`, `contentinfo`, `main`, `navigation`, `search`. - For touch events, at least one of the following must be true ([WCAG 2.1: Pointer Cancellation](https://www.w3.org/WAI/WCAG21/Understanding/pointer-cancellation.html)): - The down-event should not be used to trigger any action - The action is triggered on the up event and an option to abort the action before its completion is available or an option to undo the action after its completion - The up-event will undo any action that was triggered on a down event - It is essential to trigger the action on the down event. For example, playing a game or a piano application. - Touch targets must be large enough for the user to interact with (see the [BBC Mobile Accessibility Guidelines](https://www.bbc.co.uk/accessibility/forproducts/guides/mobile/target-touch-size) for useful touch target size guidelines). > **Note:** The [original version of this document](https://yzen.github.io/firefoxos/2014/04/30/mobile-accessibility-checklist.html) was written by [Yura Zenevich](https://yzen.github.io/).
0
data/mdn-content/files/en-us/web/accessibility
data/mdn-content/files/en-us/web/accessibility/keyboard-navigable_javascript_widgets/index.md
--- title: Keyboard-navigable JavaScript widgets slug: Web/Accessibility/Keyboard-navigable_JavaScript_widgets page-type: guide --- <section id="Quick_links"> {{ListSubpagesForSidebar("Web/Accessibility", 1)}} </section> Web applications often use JavaScript to mimic desktop widgets such as menus, tree views, rich text fields, and tab panels. These widgets are typically composed of {{ HTMLElement("div") }} and {{ HTMLElement("span") }} elements that do not, by nature, offer the same keyboard functionality that their desktop counterparts do. This document describes techniques to make JavaScript widgets accessible with the keyboard. ## Using tabindex By default, when people use the tab key to browse a webpage, only interactive elements (like links, form controls) get focused. With the `tabindex` [global attribute](/en-US/docs/Web/HTML/Global_attributes), authors can make other elements focusable, too. When set to `0`, the element becomes focusable by keyboard and script. When set to `-1`, the element becomes focusable by script, but it does not become part of the keyboard focus order. The order in which elements gain focus when using a keyboard, is the source order by default. In exceptional circumstances, authors may want to redefine the order. To do this, authors can set `tabindex` to any positive number. > **Warning:** avoid using positive values for `tabindex`. Elements with a positive `tabindex` are put before the default interactive elements on the page, which means page authors will have to set (and maintain) `tabindex` values for all focusable elements on the page whenever they use one or more positive values for `tabindex`. The following table describes `tabindex` behavior in modern browsers: <table> <thead> <tr> <th><code>tabindex</code> attribute</th> <th>Focusable with mouse or JavaScript via <code>element.focus()</code></th> <th>Tab navigable</th> </tr> </thead> <tbody> <tr> <td>not present</td> <td>Follows the platform convention of the element (yes for form controls, links, etc.).</td> <td>Follows the platform convention of the element.</td> </tr> <tr> <td>Negative (i.e. <code>tabindex="-1"</code>)</td> <td>Yes</td> <td>No; author must focus the element with <a href="/en-US/docs/Web/API/HTMLElement/focus"><code>focus()</code></a> in response to arrow or other key presses.</td> </tr> <tr> <td>Zero (i.e. <code>tabindex="0"</code>)</td> <td>Yes</td> <td>In tab order relative to element's position in document (note that interactive elements like {{HTMLElement('a')}} have this behavior by default, they don't need the attribute).</td> </tr> <tr> <td>Positive (e.g. <code>tabindex="33"</code>)</td> <td>Yes</td> <td><code>tabindex</code> value determines where this element is positioned in the tab order: smaller values will position elements earlier in the tab order than larger values (for example, <code>tabindex="7"</code> will be positioned before <code>tabindex="11"</code>).</td> </tr> </tbody> </table> ### Non-native controls Native HTML elements that are interactive, like {{ HTMLElement("a") }}, {{ HTMLElement("input") }} and {{ HTMLElement("select") }}, are already accessible by keyboards, so to use one of them is the fastest path to make components work with keyboards. Authors can also make a {{ HTMLElement("div") }} or {{ HTMLElement("span") }} keyboard accessible by adding a `tabindex` of `0`. This is particularly useful for components that use interactive elements that do not exist in HTML. ### Grouping controls For grouping widgets such as menus, tablists, grids, or tree views, the parent element should be in the tab order (`tabindex="0"`), and each descendant choice/tab/cell/row should be removed from the tab order (`tabindex="-1"`). Users should be able to navigate the descendant elements using arrow keys. (For a full description of the keyboard support that is normally expected for typical widgets, see the [WAI-ARIA Authoring Practices](https://www.w3.org/WAI/ARIA/apg/).) The example below shows this technique used with a nested menu control. Once keyboard focus lands on the containing {{ HTMLElement("ul") }} element, the JavaScript developer must programmatically manage focus and respond to arrow keys. For techniques for managing focus within widgets, see "Managing focus inside groups" below. ```html <ul id="mb1" tabindex="0"> <li id="mb1_menu1" tabindex="-1"> Font <ul id="fontMenu" title="Font" tabindex="-1"> <li id="sans-serif" tabindex="-1">Sans-serif</li> <li id="serif" tabindex="-1">Serif</li> <li id="monospace" tabindex="-1">Monospace</li> <li id="fantasy" tabindex="-1">Fantasy</li> </ul> </li> <li id="mb1_menu2" tabindex="-1"> Style <ul id="styleMenu" title="Style" tabindex="-1"> <li id="italic" tabindex="-1">Italics</li> <li id="bold" tabindex="-1">Bold</li> <li id="underline" tabindex="-1">Underlined</li> </ul> </li> <li id="mb1_menu3" tabindex="-1"> Justification <ul id="justificationMenu" title="Justification" tabindex="-1"> <li id="left" tabindex="-1">Left</li> <li id="center" tabindex="-1">Centered</li> <li id="right" tabindex="-1">Right</li> <li id="justify" tabindex="-1">Justify</li> </ul> </li> </ul> ``` #### Disabled controls When a custom control becomes disabled, remove it from the tab order by setting `tabindex="-1"`. Note that disabled items within a grouped widget (such as menu items in a menu) should remain navigable using arrow keys. ## Managing focus inside groups When a user tabs away from a widget and returns, focus should return to the specific element that had focus, for example, the tree item or grid cell. There are two techniques for accomplishing this: 1. Roving `tabindex`: programmatically moving focus 2. `aria-activedescendant`: managing a 'virtual' focus ### Technique 1: Roving tabindex Setting the `tabindex` of the focused element to "0" ensures that if the user tabs away from the widget and then returns, the selected item within the group retains focus. Note that updating the `tabindex` to "0" requires also updating the previously selected item to `tabindex="-1"`. This technique involves programmatically moving focus in response to key events and updating the `tabindex` to reflect the currently focused item. To do this: Bind a key down handler to each element in the group, and when an arrow key is used to move to another element: 1. programmatically apply focus to the new element, 2. update the `tabindex` of the focused element to "0", and 3. update the `tabindex` of the previously focused element to "-1". Here's an example of a [WAI-ARIA tree view](https://files.paciellogroup.com/training/WWW2012/samples/Samples/aria/tree/index.html) using this technique. ### Tips #### Use element.focus() to set focus Do not use `createEvent()`, `initEvent()` and `dispatchEvent()` to send focus to an element. DOM focus events are considered informational only: generated by the system after something is focused, but not actually used to set focus. Use `element.focus()` instead. #### Use onfocus to track the current focus Don't assume that all focus changes will come via key and mouse events: assistive technologies such as screen readers can set the focus to any focusable element. Track focus using `onfocus` and `onblur` instead. `onfocus` and `onblur` can now be used with every element. There is no standard DOM interface to get the current document focus. If you want to track the focus status, you can use the [document.activeElement](/en-US/docs/Web/API/Document/activeElement) to get the active element. You can also use [document.hasFocus](/en-US/docs/Web/API/Document/hasFocus) to make sure if the current document focus. ### Technique 2: `aria-activedescendant` This technique involves binding a single event handler to the container widget and using the `aria-activedescendant` to track a "virtual" focus. (For more information about ARIA, see this [overview of accessible web applications and widgets](/en-US/docs/Web/Accessibility/An_overview_of_accessible_web_applications_and_widgets).) The `aria-activedescendant` property identifies the ID of the descendant element that currently has the virtual focus. The event handler on the container must respond to key and mouse events by updating the value of `aria-activedescendant` and ensuring that the current item is styled appropriately (for example, with a border or background color). ## General Guidelines ### Use onkeydown to trap key events, not onkeypress IE will not fire `keypress` events for non-alphanumeric keys. Use `onkeydown` instead. ### Ensure that keyboard and mouse produce the same experience To ensure that the user experience is consistent regardless of input device, keyboard and mouse event handlers should share code where appropriate. For example, the code that updates the `tabindex` or the styling when users navigate using the arrow keys should also be used by mouse click handlers to produce the same changes. ### Ensure that the keyboard can be used to activate element To ensure that the keyboard can be used to activate elements, any handlers bound to mouse events should also be bound to keyboard events. For example, to ensure that the Enter key will activate an element, if you have an `onclick="doSomething()"`, you should bind `doSomething()` to the key down event as well: `onkeydown="return event.keyCode !== 13 || doSomething();"`. ### Always draw the focus for tabindex="-1" items and elements that receive focus programmatically IE will not automatically draw the focus outline for items that programmatically receive focus. Choose between changing the background color via something like `this.style.backgroundColor = "gray";` or add a dotted border via `this.style.border = "1px dotted invert"`. In the dotted border case you will need to make sure those elements have an invisible 1px border to start with, so that the element doesn't grow when the border style is applied (borders take up space, and IE doesn't implement CSS outlines). ### Prevent used key events from performing browser functions If your widget handles a key event, prevent the browser from also handling it (for example, scrolling in response to the arrow keys) by using your event handler's return code. If your event handler returns `false`, the event will not be propagated beyond your handler. For example: ```html <span tabindex="-1" onkeydown="return handleKeyDown();">…</span> ``` If `handleKeyDown()` returns `false`, the event will be consumed, preventing the browser from performing any action based on the keystroke. ### Don't rely on consistent behavior for key repeat, at this point Unfortunately `onkeydown` may or may not repeat depending on what browser and OS you're running on.
0
data/mdn-content/files/en-us/web/accessibility
data/mdn-content/files/en-us/web/accessibility/understanding_colors_and_luminance/index.md
--- title: "Web Accessibility: Understanding Colors and Luminance" slug: Web/Accessibility/Understanding_Colors_and_Luminance page-type: guide --- <section id="Quick_links"> {{ListSubpagesForSidebar("Web/Accessibility", 1)}} </section> While understanding color, luminance, and saturation is important for design and readability for all sighted users, they are essential for those with reduced vision and color-deficient vision and those with specific neurological, cognitive, and other impairments. Accessibility guidelines define adequate [color contrast](/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable/Color_contrast) for sighted users with reduced vision, as well as guidelines intended to help users with color insensitive vision, commonly referred to as "color blindness". Understanding color is also important in preventing [seizures and other physical reactions](/en-US/docs/Web/Accessibility/Seizure_disorders) in people with vestibular disorders or other neurological disorders. ## Overview The choice of colors and their use is a significant component of accessibility. On the surface, the subject seems simple. Still, it is a complex subject because color perception is as much about the physiology of the eye and human brain processing as it is about light emitting from a computer screen. ### Environment and perception Environment matters. Perception of color in a well-lit room will be different than perception of that same color on that same computer screen in a dark room. Regarding accessibility, using certain color combinations has more impact than others. Font size, [font style](https://www.nngroup.com/articles/glanceable-fonts/) (some fonts are so thin or fancy that they present accessibility problems on their own), background color, the size of the background space around the text, even pixel densities, and more all affect how color is delivered from the screen. A viewer's distance from the screen, the ambient background, the health of his eyes, and more all affect how that color is received by the viewer. How the viewer perceives color after it gets to their eyes is yet another matter, and can be affected by overall health. Fortunately, there are [media queries](/en-US/docs/Web/CSS/@media) that enable developers to provide styles based on user preferences, including [contrast](/en-US/docs/Web/CSS/@media/prefers-contrast) and [color scheme](/en-US/docs/Web/CSS/@media/prefers-color-scheme) preferences. When supported, the [Ambient Light Sensor](/en-US/docs/Web/API/AmbientLightSensor) interface returns the current light level or illuminance of the ambient light around the hosting device, enabling a web page to be aware of any change in the light intensity, and consequently, adjust the text accordingly. Additionally, the above media queries enable developers to provide alternative user experiences when user preferences indicate preferred contrast levels, automatically adjusting levels depending on the user's location and what kind of screen they are using. ### Luminance and perception Color, contrast, and luminance are the most central and critical concepts to creating accessible web content with color. Luminance is of particular importance, however, because understanding what it is and how it is employed enables accessibility for those who are color-blind, as well as those who can perceive color. The luminance contrast enables the color blind to distinguish dark from light. Luminance must be established before the contrast may be. When speaking of color contrast, W3C formulas are incorporating luminance, not just the colors ("hues") themselves. ### Terminology Terminology can be confusing because different terms often describe the same thing. "Luminance" and "Saturation" are particularly important to get right. For example, "saturation" is known as "chroma" in some circles. In others, "chroma" and "saturation" are two different concepts. The "L" in the HSL color space is sometimes referred to as "luminosity," and other times as "lightness." Even something seemingly simple, like naming common colors, can be open to debate. For example, the color "crimson red" may be described in hex values as `#990000` by some and `#DC143C` by others. For this document, we'll use terminology as it is defined in the W3C, in the [CSS Color Module Level 4](https://www.w3.org/TR/css-color-4/) When working with color, it's important to know which "color space" you are working in, as different color spaces map to different measurement systems. In color printing, your printer likely has cyan, magenta, yellow, and black (CMYK) ink cartridges. CMYK is a subtractive model wherein the four inks _remove_ specific wavelengths of light, reflecting only the narrow range each is associated with. RGB is an additive color model that adds different proportions of red, green, and blue lights. Currently, the RGB color space predominates as the space web developers work in. While HEX, RGB, and HSL color spaces are notated differently, browsers automatically convert values between these color notations. [CSS color modules](/en-US/docs/Web/CSS/CSS_colors) provide additional color spaces. Still, because of the current domination of the RGB color space in measuring color output, most calculations in this document are presumed to be in the RGB color space and, very specifically, in the sRGB color space. ## The sRGB color space Color has many ways of being defined, as is apparent in the [`<color>` data type](/en-US/docs/Web/CSS/color_value), including RGB, RGB decimal, RGB percent, HSL, HWB, LCH, and CMYK, among others. For digital concerns, much of the technology has historically resided in the RGB color space. The RGB color model is extended to include "alpha" — RGBA — to allow specification of the opacity of a color. Other methods for measuring color involve measurements using other color spaces and are supported in modern displays and browsers. Still, color measurements in the RGB color space predominate, including in video production. Technologies, such as [OpenGL](https://en.wikipedia.org/wiki/OpenGL) and [Direct3D](https://en.wikipedia.org/wiki/Direct3D) incorporate support for the sRGB gamma curve, although some articles for OpenGL reference use of RGBA rather than sRGB. WebGL is usually in the RGBA format; see an example of how it is used in "[Clearing with colors](/en-US/docs/Web/API/WebGL_API/By_example/Clearing_with_colors)". ### CSS color values It's important to know that there are variations even within one color space, such as the RGB color space. For example, variations of the RGB color space include **RGB**, **sRGB**, **Adobe RGB**, **Adobe Wide Gamut RGB**, and **RGBA**, among others. These are examples of the CSS notations used to define a color. Here the example color for each is a fully opaque magenta: ```css /* named color */ color: magenta; /* sRGB value with percentage values */ color: rgb(100% 0% 100%); color: rgb(100% 0% 100% / 100%); /* by sRGB numeric values */ color: rgb(255 0 255); color: rgb(255 0 255 / 1); /* legacy rgba notation */ color: rgba(100%, 0%, 100%, 100%); color: rgba(255, 0, 255, 1); /* by sRGB value in hex */ color: #f0f; /* #rgb, a shorthand for #rrggbb */ color: #ff00ff; /* #rrggbb */ color: #f0ff; /* #rgba */ color: #ff00ffff; /* #rrggbbaa */ /* by HSL representation of the sRGB value */ color: hsl(300 100% 50%); color: hsl(300deg 100% 50% / 100%); /* by HWB representation of the sRGB value */ color: hwb(300deg 0% 0%); color: hwb(300 0% 0% / 1); ``` The first example uses one of the defined [named colors](/en-US/docs/Web/CSS/named-color). We can set the sRGB values directly as a percentage, with 0% being off (black) and 100% being the full value for that color. The values are in the order of red, green, and blue. We can also set the sRGB values directly by a number from 0 to 255. Shown after that are hex color values. Hexadecimal is a numbering system with base-16, where the 0-255 integer is represented by two digits ranging from 0-15 using the digits 0-9 and a-f for 10-15. Thus, `ff` = `255`, `00` = `0`, and `d5` = `200`. The '#' symbol precedes the color to indicate the value is hex. If all values are pairs of identical digits, the value can be represented by single digits that the browser will duplicate. Thus `f00` is the same as `ff0000`. If a fourth set of numbers is present, that value is the A in RGBA, the alpha channel defining transparency in terms of the opacity value of the color. A higher value means the color is more opaque and therefore, less transparent. In the examples above, the alpha value is `f`, `ff`, `1`, and `100%` for fully opaque. The examples also show the legacy [`rgba()`](/en-US/docs/Web/CSS/color_value/rgb#legacy_syntax_rgba) syntax. The older syntax for color functions was comma-separated, with separate functions for when the alpha channel was included. New color functions only have one syntax with space-separated (rather than comma-separated) values, with the alpha channel, if present, being preceded by a slash. The following examples show "HSL", which stands for _Hue, Saturation, and Lightness_. HSL color values are considered by many to be more intuitive than RGB values. The color produced from the settings are still in the sRGB colorspace, but [`hsl()`](/en-US/docs/Web/CSS/color_value/hsl) is an intuitive syntax for many. The hue is adjusted as an angle, and it is easy to create a user interface using a knob or circular control to adjust the hue. Do note that HSL colors incorporate _lightness_, not _luminance_, which is a significant consideration. The last examples shows "HWB" which stands for _Hue, Whiteness, and Blackness_. Unlike `rgba()` and `hsla()`, [`hwb()`](/en-US/docs/Web/CSS/color_value/hwb) does not have a legacy `a` syntax and does not support comma-separated values. With both `hsl()` and `hwb()` the first value can be a [`<number>`](/en-US/docs/Web/CSS/number) or an [`<angle>`](/en-US/docs/Web/CSS/angle) value. When unitless, the value is interpreted as `deg` degrees. ### Conversions As we saw, one color within the same color space may be expressed in many ways. Looking at how the RGB color space is used to describe the color "magenta", you can see that the same color may be expressed in a shorthand, three-digit hex number that converts to an rgb value as a six-digit hex number that also converts to the same rgb value, or as a rgba value, expressed in percentages. RGB is hardware-oriented, reflecting the use of CRTs. Many developers and designers prefer the intuitiveness of [`hsl()`](/en-US/docs/Web/CSS/color_value/hsl) notation. Converting from RGB to HSL is not a simple equation. Fortunately, browsers do it automatically, and shift-clicking on colors in browser developer tools provides conversion functionality. In addition to developer tools, many tools can convert RGB to HSL for you and provide both the RGB hexadecimal and CSS function syntax. A great example of a tool that converts colors for you is Tom Jewett's "[mini color selector](https://colortutorial.design/microColorsC.html)" with HSL, RGB, and Hex options for checking contrast in the browser. Note that developer tools color pickers and this tool all provide WCAG [color contrast](https://webaim.org/resources/contrastchecker/) values. ![Color picker with HSL and RGB, with color contrast values.](microcolorsc.jpg) As noted earlier, the [CSS color module](/en-US/docs/Web/CSS/CSS_colors) includes adding additional colorspaces, including [`lch()`](/en-US/docs/Web/CSS/color_value/lch) functional color notation and the [`lab()`](/en-US/docs/Web/CSS/color_value/lab) color coordinate system which can specify any visible color, but because of its ubiquity, sRGB is the default and preferred colorspace for accessibility. Where accessibility is concerned, however, standards and guidelines are currently written predominantly using the sRGB color space, especially as it applies to color contrast ratios. > **Note:** Almost all systems used today to view Web content assume sRGB encoding. Unless it is known that another color space will be used to process and display the content, authors should evaluate using sRGB colorspace. If using other color spaces, apply the principles of [minimum contrast ratios](https://webaim.org/articles/contrast/#sc143). [CSS Color Module Level 5](https://drafts.csswg.org/css-color-5/) introduced [`lch()`](/en-US/docs/Web/CSS/color_value/lch) functional color notation and the [`lab()`](/en-US/docs/Web/CSS/color_value/lab) color coordinate system which can specify any visible color. These will change the domination of the sRGB color space in the future, but we are not there yet. ### Querying color values The {{domxref('Window.getComputedStyle()')}} method returns values using the RGB Decimal Reference scale. For example, calling `Window.getComputedStyle()` on a div with a `background-color: #990000;` set returns the computed background color as `rgb(153 0 0)` — the RGB Decimal reference. Being tied to computer hardware,`Window.getComputedStyle()` measures color in terms of RGB, not how the human eye perceives color. ### Red / green color blindness Protanopia is a color vision deficiency in which the eye has no red cones; sRGB can still be perceived via green cones, though darker than normal vision. Both protan (red deficient) and deutan (green deficient) deficiencies cause difficulty distinguishing _between_ red and green. Developer tools can help simulate color vision differences right in your browser. For example, Firefox's Accessibility Inspector enables simulating protanopia, deuteranopia, tritanopia, achromatopsia, and contrast loss right in the accessibility panel. ![Snippet of Firefox developer tools showing the simulate popup](simulate_color_differences.jpg) ## Luminance and Contrast ### Contrast The contrast between colors ("hues") is a critical component, but the use of color ("hues") alone is not enough to create accessible content. As mentioned before, any calculation of contrast must include luminance. In addition, the "shape" of the text itself will matter. Thin letters will be harder to read than thick ones; all typefaces need space to "breathe" for human perception. ### Contrast and font size [WCAG contrast guidelines](/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable#guideline_1.4_make_it_easier_for_users_to_see_and_hear_content_including_separating_foreground_from_background) define "large" text as text that is `18pt` (approximately `24px`) or larger when {{cssxref('font-weight')}} is `normal` and `14pt` (approximately `18.7px`) for `bold` text. Stating: _Text that is larger and has wider character strokes is easier to read at lower contrast. Therefore, the contrast requirement for larger text is lower. This allows authors to use a wider range of color choices for large text, which is helpful for the design of pages, particularly titles._ While larger text does not require as great color contrast with its background as smaller text, increasing font size is not a panacea. "Normal" print is usually considered 11.5pt to 12pt, equivalent to 16px on screen. While smaller font may be legible — a user can make out letters at \~70% accuracy — that is not readable. A 16px font size is generally readable for people with normal vision. Someone with 20/40 needs twice that, about a 31px font. This is why the WCAG guidelines require that users have the ability to zoom any text larger. While a text displayed too small is hard to read, so is a text that is too large. For users with 20/20 vision, with a text size greater than approximately 96px, reading speed decreases. Also, when there is a large disparity between the smallest and largest font size on a page, the larger text will become less readable if users enlarge the smaller text on the page, as most browsers zoom all text as the user zooms. In general, for accessibility purposes, the more contrast, the better. That changes with animation. "Safer" animation means images with less contrast, not more. For more on color contrast in animation, see [Three Flashes or Below Threshold Understanding SC 2.3.1](https://www.w3.org/TR/UNDERSTANDING-WCAG20/seizure-does-not-violate.html) Also, note that icons need sufficient contrast for perception. See [WCAG 2.1 technique G207](https://www.w3.org/WAI/WCAG21/Techniques/general/G207) ### Luminance It is the difference in the luminance of a color that enables us to see the contrast. Relative luminance is defined in WCAG as "the relative brightness of any point in a colorspace, normalized to 0 for darkest black and 1 for lightest white." This statement is of course accurate, but may be confusing when used in reference to the RGB color space, which is an integer between 0 and 255. White has 100% relative luminance, black has 0% relative luminance (in most but not all literature). Interpreting for the W3C standard above, that would mean that white, normalized to 1, would have an RGB value of `rgb(255 255 255)` and black, normalized to 0, would have an RGB value of `rgb(0 0 0)`. Note that black and white can also be written as `rgb(100% 100% 100%)` and `rgb(0% 0% 0%)` respectively, which may be more intuitive. So, where do these numbers of 0 to 255 come from? Historically, graphics engines stored the color channels as a single byte, which means a range of integers between 0 and 255. The luminances of the primary colors are different. Yellow has a greater luminance than blue, for example. This was done by way of design, _to achieve white alignment of the monitor_, according to the NASA document, "[Luminance Contrast in Color Graphics](https://colorusage.arc.nasa.gov/design_lum_1.php)" A color contrast ratio is meaningless without its luminance component, and once luminance is established, the color contrast ratio can be established. Where human perception is concerned, a difference in luminance matters more than a color difference. This is important, as luminance contrast enables the development of content that even those with color blindness can see. With this understanding, luminance may be manipulated so that colors that are difficult to see because of their low luminance could be made more legible by placing these colors against another with contrasting luminance. An interesting study by NASA on the color blue, for example, noted that this color, which has low luminance, can be made legible if _care was taken to achieve adequate luminance contrast_ (From the article, [Designing with blue](https://colorusage.arc.nasa.gov/blue_2.php)) Calculations for relative luminance are not casual ones. Luckily, there are [online luminance and contrast checkers](https://contrast-ratio.com/) available, and even instructions on how to [calculate relative luminance](https://www.w3.org/TR/WCAG21/#dfn-relative-luminance). ## Perceiving color Color is our perception of the narrow band of visible light, from red through yellow and green to blue. Our sensitivity to these various hues of color are not equal. The light sensitive cells in our [eyes](https://www.verywellhealth.com/eye-cones-5088699), called cones, are tuned to perceive some colors more than others. About 65% of cones are _most_ sensitive to a yellow/green, but also respond to red (we'll call these "red" cones). 30% are green sensitive, and only [5% are blue sensitive](https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0144891#sec001). While there are far fewer blue-sensitive cones than the other two types, these cones are very sensitive, which partially makes up for their smaller numbers. Deep, pure blue is perceived differently than other colors as blue cones do not contribute to luminance and we have far fewer blue cones than red or green. ![On the left is a cone mosaic of standard vision, and on the right is that of someone with protanopia where they are missing the red cones.](conemosaics.jpg) On the left is the central cone mosaic of standard vision, and on the right is that of someone with protanopia, a form of color vision deficiency, where they are missing the red cones. (Illustration by Mark Fairchild of RIT, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:ConeMosaics.jpg)) The red and the green cones join together to create luminance, which we can think of as lightness/darkness without regard to hue. Separately, the red, green, and blue cones allow for standard vision to perceive millions of colors. For accessibility, it's important to know that our brain processes luminance separately from color (hue and colorfulness). Luminance provides for fine vision details, including differentiating edges and text. Hue and colorfulness carry a third of the detail of luminance. Image data compression takes advantage of this fact. As an example, [h.264 video codec](/en-US/docs/Web/Media/Formats/Video_codecs) samples color at a fourth of the resolution of the luminance. For accessibility, this means that luminance contrast is critically important for text. Color, as in hue and colorfulness, is important for _distinguishing_ items such as different lines on a map or bars in a graph. Another essential point to consider is the color or luminance that is surrounding a color. Colors appear differently depending on what is surrounding them. In the following image, both the yellow dots and the grey squares are the same sRGB color. Context-sensitive color perception makes them appear different; your brain's image processing adjusts the perception based on what it thinks is in shadow or not. ![An image of a checkerboard, where identical colors look different if they are in shadow](yellowdotcheckershadow_dlyon.png) The yellow dots in this image are identical colors on your monitor, but they appear different due to context. (Image D.Lyon) Our contrast, lightness, and color perception are affected by the context of the nearby colors and other features of a design or image. This makes predicting contrast challenging. It is not as simple as a mathematical ratio between two colors. To summarize, color is as much about human physiology and perception in the brain as it is about measuring light from a computer screen. It's also important to understand that the ambient light environment affects the ability to perceive color and contrast. Light and its measurements are linear, but human vision and perception are not. ## Adaptation Our eyes don't adapt equally, in the same way, going from light areas to dark ones and vice versa. This is due to the physiological ways our eyes are built. This affects the ability of a user to read text against a background. At least two kinds of adaptation take place: local adaptation and adaptation to an ambient environment. Local adaptation occurs right on the "page" a reader is looking at. For example, if you have blue text within a gray "highlighted" area, your eyes will perceive that exact blue text with a gray highlight differently if it is in a black {{HTMLElement("div")}}, or a white one. This is called _local_ adaptation. This difference in the ability to perceive the text is affected even though the room's ambient lighting does not change. The implication is that web developers who seek to improve the legibility of text against a background can take advantage of the principles of local adaptation. Dark adaptation to low luminance is slow. When you come in from outside, where the sun is bright, and walk into a dark room, you are experiencing dark adaptation. It can take a few minutes to adjust to this. Light adaptation is the reverse. Going from a dark room into bright sunlight is quicker but can also hurt. The implication is that web developers who seek to improve the legibility of text in which the ambient conditions of a room have changed can take advantage of the `AmbientLightSensor` interface and the [`prefers-contrast`](/en-US/docs/Web/CSS/@media/prefers-contrast) media query. ## Saturation Saturation deserves a special mention in discussions about color ("hues") and accessibility. Generally speaking, most focus is on luminance when attempting to ensure enough contrast between text and its background or evaluating the possibility of inducing seizures in those sensitive to photosensitive seizures. One aspect of color ("hues"), independent of luminance, deserves special attention as it applies to accessibility: the concept of saturation. This is due to its ability to cause seizures in those susceptible to photosensitive seizures, regardless of color's luminance. As discussed in [the particular case of red](#the_special_case_of_red), the [Epilepsy Foundation](https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.532.7063&rep=rep1&type=pdf) noted that, _irrespective of luminance, a transition to or from a saturated red is also considered a risk_. Saturation is sometimes described as the "purity" or "intensity" of a color. Although these are good definitions for "pigments" in an artist's paint set, they are not as accurate as color definitions from a computer screen. When it comes to color on a monitor, saturated colors are of a particular wavelength. While the definition of saturation for each color space may differ, saturation is readily measured. The key is to know which color space you are working in and be ready to convert it if necessary. The color spaces most frequently considered when discussing photosensitivity are the RGB, HSL, and HSV, also known as HSB, color spaces. The HSV color space, which stands for _hue_, _saturation_, and _value_, and the synonym HSB, which stands for _hue_, _saturation_, and _brightness_), are represented in CSS as [`hwb()`](/en-US/docs/Web/CSS/color_value/hwb) for _hue_, _whiteness_, and _blackness_. It's important to know what color space you're working with. For example, saturated colors have a lightness of `0.5` in HSL, while in HWB, they have a value `1`. Saturation in the RGB color space is usually indicated by an RGB value of `255` or `100%` for the color in question. For example, a saturated red of hex value `#ff0000` has an RGB value of `rgb(255 0 0)` and an HSL value of `hsl(0 100% 50%)`. A different saturated red with a hex value of `#ff3300` has an RGB value of `rgb(255 51 0)` and an HSL value of `hsl(12 100% 50%)`. Both are "saturated" reds. They are two different "hues" but are both considered to be a saturated color. Saturation is not brightness. Brightness refers to how much white or black is mixed in with a color. One can decrease saturation by adding white, black, or gray to the color; to take the example further, brightness can be increased by adding white, reducing saturation. A typical example is to add white to red to get the color pink. Pink is considered a desaturated red. ### Saturation and luminance There is a loss of saturation at the extremes of luminance and the extremes of black and white. In NASA's [effect of luminance on saturation](https://colorusage.arc.nasa.gov/design_lum_1.php), they point out that there is a loss of saturation at low luminances. and also, "…the loss of saturation at high luminances–the colors converge on white." ## Color combinations Contrast alone is not enough when it comes to accessibility considerations. In the case of animation, certain color combinations are more likely to cause photosensitive seizures to those who are susceptible to them than others. For example, alternating flashes between red and blue is more problematic than alternating flashes between green and blue. It has been theorized that this is because the "red" sensitive cones of our eyes, which tend to cluster around the fovea (near the center), are physically located at a different location than the "blue" sensitive cones of our eyes, which are located away from the fovea and towards the rims. The electrical signals from the eye to the brain have much to resolve between them as the information is processed in our brains. Some colors more likely to [cause epileptic seizures](https://www.epilepsy.com/sites/default/files/2022-10/Epilepsia_2022_fisher_visually_sensitive_seizures.pdf). Complexities underlying brain dynamics can be modulated by some color combinations more than the others. For example, red-blue flickering stimulus causes larger cortical excitation than red-green or blue-green stimulus. Certain color combinations can be very problematic on a computer monitor or mobile device, and some color combinations can interfere with some impairments. The combination of red/blue is one such example. - Never rely on hue alone for differentiating details. Adequate luminance contrast is required. - The green in a monitor makes up the vast majority of luminance (light), so it will usually be a significant part of the lighter colors. ### Working with blue Some people cannot differentiate between all colors. Some colors, such as pure blue, are low in luminance. Colors that are low in luminance should be the darker of contrasting colors. Blue is also very low in resolution. There are far fewer blue cones, and they are scattered in our peripheral vision and not present in our central vision. The human eye sees blue at a lower resolution than green and red. This leads to some blue color use guidelines: - Pure blues should typically be the darkest of two colors. - When using blue as the lighter of the two colors, add green to increase contrast and improve readability. The nature of blue light causes it to focus at a different location on the retina than red, so a pure red and a pure blue color that are immediately adjacent and touching may "shimmer" when next to each other. ## The special case of red Not all colors ("hue") are processed similarly by our brains. Human physiology and psychology are affected by the color red, generally speaking, in ways different from that of other colors. We respond physiologically as well as psychologically to colors. For example, it has been demonstrated that [some colors are more likely to cause epileptic fits than others](https://www.sciencedaily.com/releases/2009/09/090925092858.htm). Some devices offer a ["grayscale" setting as an accessibility option](https://ask.metafilter.com/312049/What-is-the-grayscale-setting-for-in-accessibility-options)" which can help people who are photo-sensitive. To mimic the grayscale setting, use the CSS {{cssxref("filter")}} property with a [`grayscale()`](/en-US/docs/Web/CSS/filter-function/grayscale) or [`saturate()`](/en-US/docs/Web/CSS/filter-function/saturate) [`<filter-function>`](/en-US/docs/Web/CSS/filter-function). ### Saturated red "Saturated Red" is a special, dangerous case, and there are special tests for it. The concept of color saturation is a difficult one to understand when only looking at numbers and terminology, so consider looking at the image below to illustrate the concept of saturation in a color: ![Red Saturation from Wikimedia Commons svg saved as png Attribution: Datumizer [CC0]](320px-red_saturations.svg.png) The same "color" proceeds from least saturated on the left-hand side to most saturated on the right-hand side. _More than one "red" color may be considered a "saturated" red._ For example, the color `#990000` at `hsl(0 100% 30%)` is fully saturated but is less bright than the colors described above. Similarly, the color `#8b0000` also has a saturation of 100%. Not all saturated reds may be represented well in the RGB spectrum or other spectrums commonly used in web development. According to Wikipedia's page on "Shades of Red", the color "Carmine" is a saturated red which, in its pigment form, mostly contains red light with wavelengths longer than 600nm; the article makes the special note that "Carmine" is close to the extreme spectrum. This places it far beyond standard gamuts (RGB and CMYK), and its given RGB value is a poor approximation only." ### Saturated red flashing In addition to a red environment affecting the cognitive function of those with traumatic brain injury, color in the red spectrum wavelength requires special attention and tests. Gregg Vanderheiden, when testing the _Photosensitive epilepsy analysis tool_, noted seizure rates were much higher than expected. They found that we are much more sensitive to saturated red flashing. (See the video, [The Photosensitive epilepsy analysis tool](https://www.pbs.org/video/university-place-the-photosensitive-epilepsy-analysis-tool-ep-429/).) ### Flashing and seizures Continuous flashing brighter/darker at rates higher than three flashes per second has been shown to induce photic seizures in some people. It has also been found that specific, very regular, high-contrast patterns, such as parallel white and black stripes, can also induce seizures. The Epilepsy Foundation of America researched [photic- and pattern-induced seizures](https://www.researchgate.net/publication/7615895_Photic-_and_Pattern-induced_Seizures_A_Review_for_the_Epilepsy_Foundation_of_America_Working_Group). The study resulted in several fundamental guidelines: 1. Single, double, or triple flashes in one second are acceptable, but a sequence of flashes is not recommended when more than three flashes happen within one second. 2. When displaying light and dark stripes, the pattern should display no more than five light–dark pairs of stripes, if the stripes change direction, oscillate, flash, or reverse in contrast or eight light–dark pairs of stripes, if the pattern is unchanging or continuously and smoothly drifting in one direction. The consensus recommendations are in this brief paper, [Photic- and Pattern-induced Seizures: Expert Consensus of the Epilepsy Foundation of America](https://onlinelibrary.wiley.com/doi/epdf/10.1111/j.1528-1167.2005.31405.x). Some additional insights are available in this UK paper covering [guidelines for preventing seizures.](https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.106.9473&rep=rep1&type=pdf). ## Psychophysical aspects of color Color as in hues and saturation can affect our mood, and enhance — or de-enhance — our interactive experiences. ### Examples of color's effect beyond vision - **Color can be culturally dependent:** [A Cross-Cultural Study of the Affective Meanings of Color](https://journals.sagepub.com/doi/10.1177/002202217300400201) - **Color affects our emotions:** [Color and emotion: effects of hue, saturation, and brightness](https://pubmed.ncbi.nlm.nih.gov/28612080/) - **Higher contrasts can also have a positive affect on our emotions:** [Emotion Variation from Controlling Contrast of Visual Contents through EEG-Based Deep Emotion Recognition](https://pubmed.ncbi.nlm.nih.gov/32823741/) - **Some colors can affect our perception of time:** [Color and time perception: Evidence for temporal overestimation of blue stimuli](https://pubmed.ncbi.nlm.nih.gov/29374198/) - **Blue also has a significant effect on brightness and glare:** [Blue and glare & brightness](https://pubmed.ncbi.nlm.nih.gov/31288107/) - **Red tinted glasses can provide increased happiness or joy:** [Looking Through "Rose-Tinted" Glasses: The Influence of Tint on Visual Affective Processing](https://pubmed.ncbi.nlm.nih.gov/31244627/) - **Red is well known to have significant effects on our behavior:** [How the Color Red Influences Our Behavior](https://www.scientificamerican.com/article/how-the-color-red-influences-our-behavior/), Scientific American, S. Martinez-Conde, Stephen L. Macknik - **Red Environment:** Studies have shown that for those who suffer Traumatic Brain Injury, [cognitive function is reduced in a red environment](https://www.ncbi.nlm.nih.gov/pubmed/20649469). ## See also - [Accessibility](/en-US/docs/Web/Accessibility) - [Accessibility learning path](/en-US/docs/Learn/Accessibility) - CSS [`color`](/en-US/docs/Web/CSS/color) property - [`<color>`](/en-US/docs/Web/CSS/color_value) data type - [Web accessibility for seizures and physical reactions](/en-US/docs/Web/Accessibility/Seizure_disorders) - [How the Color Red Influences Our Behavior](https://www.scientificamerican.com/article/how-the-color-red-influences-our-behavior/) Scientific American By Susana Martinez-Conde, Stephen L. Macknik on November 1, 2014 - [Red Desaturation](https://www.smart-optometry.com/red-desaturation/) The human eye is so sensitively "tuned" to red, that ophthalmologists set up a test using it, assessing the integrity of the optic nerve. - [Photic- and pattern-induced seizures: expert consensus of the Epilepsy Foundation of America Working Group](https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.532.7063&rep=rep1&type=pdf)
0
data/mdn-content/files/en-us/web/accessibility
data/mdn-content/files/en-us/web/accessibility/cognitive_accessibility/index.md
--- title: Cognitive accessibility slug: Web/Accessibility/Cognitive_accessibility page-type: guide --- <section id="Quick_links"> {{ListSubpagesForSidebar("Web/Accessibility", 1)}} </section> Cognitive accessibility covers accessibility considerations for people with cognition and learning disabilities. This document introduces cognitive accessibility and improving accessibility of the web for people with cognitive and learning differences. Cognitive impairment refers to a broad range of disabilities, from people with intellectual disabilities who may have the most-limited capabilities, to age-related issues with thinking and remembering. The range includes people with mental illnesses, such as depression and schizophrenia. It also includes people with learning disabilities, such as dyslexia and attention deficit hyperactivity disorder (ADHD). Though there is a lot of diversity within clinical definitions of cognitive impairments, people with them experience a common set of functional problems. These problems include difficulty with understanding content, remembering how to complete tasks, and confusion caused by inconsistent or non-traditional web page layouts. In this document, we focus on steps developers should take to improve the cognitive accessibility of their websites and applications. ## Overview Cognitive and intellectual disabilities cover a large spectrum, and may be momentary, temporary, or permanent conditions. For example, dementia and Alzheimer's are permanent cognitive impairments that get progressively worse. Other permanent cognitive impairments include aphasia, speech and language, autism, ADD/ADHD, dyslexia, and dyscalculia. An example of a temporary cognitive impairment could be people affected by substances such as alcohol or drugs. Another form it can take is depression, such as when mourning the loss of a loved one, or being momentarily saddened by a tweet or video they just saw online. A third example could be sleep deprivation. It may seem like an overwhelming challenge to address the wide range of cognitive differences, especially when solutions for two different people may be conflicting. One way to handle this is to focus on cognitive skills. Cognitive skills include: - attention - memory - processing speed - time management - letters and language - numbers symbols and math - understanding and making choices A solid approach to providing accessible solutions for people with cognitive impairments includes: - delivering content in more than one way, such as by text-to-speech or by video; - providing easily-understood content, such as text written using plain-language standards; - focusing attention on important content; - minimizing distractions, such as unnecessary content or advertisements; - providing consistent web page layout and navigation; - incorporating familiar elements, such as underlined links that are blue when not visited and purple when visited; - dividing processes into logical, essential steps with progress indicators; - making website authentication as easy as possible without compromising security; and - making forms easy to complete, such as with clear error messages and simple error recovery. ## WCAG Guidelines WCAG, Web Content Accessibility Guidelines, includes several guidelines to improve cognitive accessibility. These guidelines are published by the Web Accessibility Initiative (WAI) of the World Wide Web Consortium (W3C), the main international standards organization for the Internet. This group is also responsible for the [Accessible Rich Internet Application (ARIA)](/en-US/docs/Web/Accessibility/ARIA/ARIA_Guides) guidelines. WCAG are guided by four principles: websites must be Perceivable, Operable, Understandable, and Robust. To this end, they define 17 specific guidelines, of which six are especially relevant for cognitive accessibility. All of the following guidelines help more than just people with cognitive disabilities. For example, being able to extend the expiration time on an application requiring an authentication code sent to a mobile device via text message helps with the following scenarios: - People with attention or anxiety disorders. - People who have a poor short-term memory, or who are multitasking. - People who are less technologically literate. - People who have poor wireless reception. - People who have motor control issues. ## Adaptability [Guideline 1.3](https://www.w3.org/WAI/WCAG21/Understanding/adaptable) states "content should be **adaptable**". Create content that can be presented in different ways without losing information or structure. For example, provide {{glossary('responsive web design', 'responsive')}} layouts, with a single column mobile design. All information, including structure and relationships conveyed through the presentation, should be available in a form that can be perceived by all users to achieve this goal. For example, the information could be spoken aloud via a narration tool. Making your content capable of being understood by the software is a good way to help ensure it can be used by alternate presentational modes. ## Time It is important to allow users the time they require to complete tasks. [Guideline 2.2](https://www.w3.org/WAI/WCAG21/Understanding/enough-time) states "provide users enough **time** to read and use content". A **time limit** is any process that happens without user initiation after a set time or on a periodic basis, such as being logged out after 30 minutes or having 15 minutes to make a purchase. People with cognitive disabilities may require more time to read content, or to perform functions such as filling out forms. Solutions include providing users enough additional time to complete tasks or eliminate time constraints altogether. ### Timers Options for adjusting time requirements include: - Allowing the user to turn off or adjust the time to at least 10 times the original limit before encountering it. - Alerting the user and providing a buffer of at least 20 seconds to extend the timeout duration by a factor of 10 with a simple action, such as hitting the space bar. Provide a toggle on content that allows users to enable a longer session time limit, or no session time limit at all. Examples of timed content include forms, timed reading exercises, and training materials. If the time limit is longer than 20 hours, accommodations are not required. ### Moving, blinking, scrolling It is important not to distract users, especially ones with cognitive disabilities. If moving, blinking, scrolling, or auto-updating information starts automatically, lasts more than five seconds, and is presented in parallel with other content, the user must able to pause, stop, hide or control it, unless it's an essential functionality. "Essential" means that removing the moving, blinking, scrolling, or auto-updating information would fundamentally change the meaning of the content and/or functionality, **and** information and functionality cannot be achieved in another way that would conform. This includes animated gifs, if the gif animates for more than 5 seconds. Additional timing criteria to consider are: - People who have cognitive or language limitations may need more time to read and to understand. For improved usability remove any time limit. Timed content should also be avoided, with exceptions for non-interactive synchronized media and real-time events. - People with attention deficit disorders should be able to focus on content without distractions. The user should be able to postpone or suppress interruptions, except situations involving alerting a person to an emergency. This provides access to people with cognitive disabilities by enabling them to focus on the main purpose of the content. Enable the user to postpone content updates by providing a way to request content updates rather than updating automatically. Also, enable a way to make nonessential alerts optional. - Ensure that people can continue an activity without loss of data after re-authenticating an expired session, for example, saving the state of a questionnaire. Make sure to save data in such a way that it can be modified after a user re-authenticates. Before re-authenticating, encode the data as hidden or encrypted. - Providing warnings about inactivity that could result in data loss. When a timeout is used, tell people exactly how much time will cause the session to time out and result in lost data. The exception to this is preserving data for more than 20 hours when no actions are taken. ## Navigation [Guideline 2.4](https://www.w3.org/WAI/WCAG21/Understanding/navigable) states "provide ways to help users navigate, find content, and determine where they are," and provides 10 guidelines to ensure the site is navigable and content is findable: ### Include a `<title>` Make sure to include a {{HTMLElement('title')}} for the document, as titles provide a quick and easy to reference description of the screen's main point. People with cognitive disabilities, limited short-term memory, and reading disabilities all benefit from being able to identify the purpose of content this way. ### Heading and labels Include clear and descriptive headings so users can easily find information and understand relationships between different content sections. Descriptive labels help users identify specific components within the content. People who read slowly and people with limited short-term memory benefit when section titles make it possible to predict what each section contains. ### Section headings Headings help define overall organization of page content. They help facilitate navigation through page content sections, and provide a mechanism to aid comprehension. Examples of headings include chapters, sections and subsections of content, and so on. Headings are more obvious navigational aids compared to other methods to identify page content sections (borders, whitespace, horizontal rules, etc.). ### Multiple ways to find content Different users prefer different methods of finding information, so it is important to provide multiple ways for users to locate content on your site. Providing more than one way to navigate your site can help people find information faster. Some users may prefer a table of contents, site map, or search functionality rather than reading and traversing through several pages to find what they need. Others may prefer to explore the site in a sequential manner, moving from page to page in order to best understand the site's layout, content, and concepts. ### Ability to bypass blocks of content Providing a mechanism, such as a [skip link](/en-US/docs/Web/HTML/Element/a#skip_links), to bypass blocks of content that are repeated on multiple web pages. ### Focus order makes sense The order of focus for interactive elements should make sense. To achieve this, the DOM order should match the visual order, which in turn should match the tabbing order. If the tab order jumps around, especially in a way that does not match the visual order when navigating with a keyboard, users can become disoriented. ### Focused elements should be visibly focused When a user navigates using a keyboard, the UI should make it obvious which element currently has focus. Don't alter or remove the browser's default [`:focus`](/en-US/docs/Web/CSS/:focus) styling, unless you're making focus even more obvious. ### Link text conveys meaning The link's text should clearly and concisely communicate what the user should expect to be navigated to next if they choose to activate it. Poorly phrased link text may confuse users as to its purpose or destination. Some forms of assistive technology allow users to navigate by lists of all the links present on the page. Links will be removed from the context of their surrounding non-link content, making the need for understandable link text even more important. An example of a poor experience is a page full of links whose text reads, "Click here". Without indicating where "here" will take you, the link's purpose is unclear. For screen readers, it is vital that linked text describes the purpose of each link. If you have added content to links for screen readers, and that content is verbose and potentially confusing to sighted readers, consider clipping the added text to visually hide it from those not using assistive technologies. ### Current location is available Users should be able to orient themselves within a site or application. This is especially important and helpful for people with short attention spans who may become confused when following a long series of navigation steps. All users benefit from information about where they are in a site's hierarchy, especially for sites or applications with large amounts of content or many subsections. [Breadcrumbs](/en-US/docs/Glossary/Breadcrumb), [site maps](/en-US/docs/Glossary/Site_map), and identifying the current page in the navigation as "current" are all techniques that help communicate the current location. ## Readability [Guideline 3.1](https://www.w3.org/WAI/WCAG21/Understanding/readable) states "make text content readable and understandable". For some users, it is difficult to infer the meaning of a word or phrase from context, especially when the word or phrase is used in an unusual way, or has been given a specialized meaning. For these users, the ability to read and understand may depend on the availability of specific definitions or the expanded forms of acronyms or abbreviations. Some users may experience great difficulty in recognizing written words yet they understand extremely complex and sophisticated documents when the text is read aloud, or when key processes and ideas are illustrated visually. ### Declare the language of the page and any content not in that main language The language of every page must be declared by using the [`lang`](/en-US/docs/Web/HTML/Global_attributes/lang) attribute on the {{HTMLElement('html')}} element. Include the `lang` attribute again on text that is in a language other than the main language of the document. Proper use of `lang` allows some screen readers to announce the text properly when converting it into synthetic speech. It also helps people who use text-to-speech software. ### Define unusual words and word usage Some disabilities make it difficult to understand nonliteral word usage, such as idioms, colloquialisms, and specialized jargon. Non-native language speakers may also struggle with these terms. If a word or phrase has a unique meaning, in the document provide a definition inline or linked, within a glossary, or to an online dictionary. If a word or phrase is used to mean more than one thing, define each use. ### Define abbreviations Abbreviations can be confusing for people who: - Have difficulty decoding words. - Have limited memory. - Have difficulty using context to aid understanding. - Rely on screen magnifiers (which often reduce contextual cues). Provide an expanded form of the abbreviation the first time it is used, followed by the abbreviation placed within an {{HTMLElement('abbr')}} element. If an abbreviation has no expanded form, or is an abbreviation for a word that is not in the document's main language (such as Latin), explain its meaning. Also, consider using [ruby text](/en-US/docs/Web/HTML/Element/ruby) for initialism (pronunciation of acronyms). ### Reading level Content should be written as clearly and as possible. A good rule to go by is to make content simple enough that it can be understood the first time. Methods to achieve this include: - Using short, simple words. - Writing short sentences. - Using active voice in the present tense. - Using correct grammar and spelling. It helps users with cognitive disabilities to provide a text summary (sometimes referred to as a TL;DR, or "too long; didn't read") at a low reading level. Another technique you can use is providing accompanying visuals to help explain ideas, events, and processes. There are tools that can rate the level of your content. For example, this document has an average grade level of about 11. This means it should be easily understood by a native English speaker aged 16 to 17. Some tools can even provide suggestions to help simplify it. ### Pronunciation There are multiple techniques that can help teach people how to pronounce words: - Provide the pronunciation immediately following the word. - Link to a list of pronunciations. - Provide a glossary with pronunciation. - Use the {{HTMLElement('ruby')}} element to illustrate how a word is pronounced. Providing guidance on how to pronounce words helps many different kinds of people, including those who prefer to read aloud, non-native language speakers, and people who may unfamiliar with the meaning of a term in context. Another solution is to use glyphs or diacritical marks to illustrate pronunciation. However, if this technique is used, there must be a mechanism to turn it off. Further, it is helpful to link to a guide to the marks being used, as their meaning may not be obvious. ## Predictability WCAG [Guideline 3.2](https://www.w3.org/WAI/WCAG21/Understanding/predictable) states "make web pages appear and operate in predictable ways". This is a tenet of good user experience design. Consistency is especially important for people with cognitive difficulties. This includes consistency in page layout and predictable interactive components. ### Use activation, not focus to change context Creating a change in context should be intentional. Because of this, when a UI feature receives [focus](/en-US/docs/Web/API/HTMLElement/focus), it should not trigger further user-facing actions. Rather, users should need to "activate" a feature to trigger the change. ### Change setting based on an active request Form control operation and data entry should result in predictable behavior. Changes in context can confuse users with cognitive disabilities, and should therefore only occur when it is clear that such a change will happen in response to the user's action. Changing state should require intentional user action. Examples of this are checking a checkbox, entering data or changing a select option. Also be sure to provide a submit button to initiate the change of context, and describe what will happen before the change is made. ### Keep navigation consistent throughout the site Keep the navigation order consistent between pages. For example, if you have a navigation bar on multiple pages, make that navigation uniform across the site with the same links in the same location. This doesn't just apply to navigation: present all repeated components in the same relative order each time they appear. ### Provide consistent labeling Identical functions should have similar labels every time they are utilized. Consistent button labels, alternative text for icons, and iconography for similar interactions and so on, even on different sections of your site, help all your users. ### Be consistent and predictable, and use norms While unlabeled iconography is not the most effective method of conveying information, keeping the use of the icons (and if labeled, their label text) consistent helps people to understand what the icon represents. Similarly, don't change defaults like the browser's back button. If you need to redirect a user, let the user know about it beforehand. ## Input Assistance [Guideline 3.3](https://www.w3.org/WAI/WCAG21/Understanding/input-assistance) helps to ensure accurate data entry, stating "help users avoid and correct mistakes". While we all make mistakes, some people are more likely to make mistakes, less likely to notice a mistake, or have a harder time correcting a mistake once they make one. Input Assistance guidelines aim to reduce the likelihood that users, especially those with disabilities, make a mistake, and, if they do make a mistake, increase the likelihood that they see and comprehend the error message and can successfully fix any errors. ### Convey automated error detection Users need to be alerted to the error and informed of what is wrong. If there is client side error detection, observe the following guidelines to make the error as effective as possible when conveyed to the user: - The error must be described in the text. - Ensure that the error message is as specific as possible. - Provide text to identify incomplete required fields and text descriptions if a value entered is invalid. - If the error prevented a form submission, focus on the error. If multiple errors are present, provide a summary, with each error linking to the related input. - Include text along with use of icons, images, color and so on. Some people have difficulty understanding the meaning of icons and other visual cues. - Other people may have difficulty understanding the text version of your error message. For these people, also provide things like icons and colors. - Also, provide feedback on when there is a successful form submission. ### Provide instructions for user input Start the form with text instructions on how to operate it. Include labels or instructions when users need to input information, using the {{HTMLElement('label')}}, {{HTMLElement('fieldset')}}, and {{HTMLElement('legend')}} elements to do so. Labels should be descriptive and positioned close to the input they relate to. When requiring a specific format for input, provide an example formatted in the proper way. Additionally, consider performing server-side validation to help format input data, to aid in the ease of user input. If a form control is required, indicate it both visually and [via code](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-required). If a form control changes context, describe what will happen in a way that the user will understand it before they cause the context change to happen. ### Error Suggestion Provide suggested input to the user if an input error is automatically detected and suggestions for correction are known (unless doing so would jeopardize the security or purpose of the content). ### Prevent catastrophes For submissions that cause, or can lead to, legal, financial, or other significant consequences, ensure that the submissions can be reviewed, confirmed, and/or are reversible. Data entered by the user should be checked for errors before submission, and the user should be given the opportunity to correct them. The user should be able to review, confirm, and correct information before final submission. Also, be sure to include a confirmation checkbox in addition to a submit button. If a submission causes a legal or financial transaction to occur, provide a stated time within which the request can be amended or canceled by the user. ### Provide help Context-sensitive help should be made available. If a form requires text input, provide form instructions describing the purpose and the necessary input. Include spell checking and suggestions for long-form text input, as well as links to help and support material. If a specific data format is expected for input, provide an example. ## Notes The above are good design practices. They will benefit everyone. - Many people with cognitive impairments also have physical disabilities. Websites must conform with the W3C's [Web Content Accessibility Guidelines](https://www.w3.org/WAI/standards-guidelines/wcag/). - The W3C's [Cognitive and Learning Disabilities Accessibility Task Force](https://www.w3.org/WAI/GL/task-forces/coga/) produces web accessibility guidelines for people with cognitive impairments. - WebAIM has a [Cognitive page](https://webaim.org/articles/cognitive/) of relevant information and resources. - The United States Centers for Disease Control estimate that, as of 2018, 1 in 4 U.S. citizens have a disability and, of them, [cognitive impairment is the most common for young people](https://archive.cdc.gov/www_cdc_gov/media/releases/2018/p0816-disability.html). - In the U.S., "intellectual disabilities" used to be called "mental retardation". In the U.K., "intellectual disabilities" is commonly called "learning disabilities" or "learning difficulties". ## See also - [Accessibility Guidelines](https://extensionworkshop.com/documentation/develop/build-an-accessible-extension/) - [What is accessibility](/en-US/docs/Learn/Accessibility/What_is_accessibility) - [Accessibility for seizure disorders](/en-US/docs/Web/Accessibility/Seizure_disorders) - [Understanding WCAG Guidelines](/en-US/docs/Web/Accessibility/Understanding_WCAG) - [Accessibility overview](/en-US/docs/Learn/Accessibility) - [Web Content Accessibility Guidelines](https://www.w3.org/WAI/standards-guidelines/wcag/), including [cognitive accessibility guidelines](#wcag_guidelines) - [CThe W3Cs cognitive and Learning Disabilities Accessibility Task Force](https://www.w3.org/WAI/GL/task-forces/coga/) - [WebAIM Cognitive information](https://webaim.org/articles/cognitive/) - [CDC information on disabilities](https://www.cdc.gov/ncbddd/disabilityandhealth/)
0
data/mdn-content/files/en-us/web/accessibility
data/mdn-content/files/en-us/web/accessibility/seizure_disorders/index.md
--- title: Web accessibility for seizures and physical reactions slug: Web/Accessibility/Seizure_disorders page-type: guide --- <section id="Quick_links"> {{ListSubpagesForSidebar("Web/Accessibility", 1)}} </section> This article introduces concepts behind making web content accessible for those with vestibular disorders, and how to measure and prevent content leading to seizures and/or other physical reactions. ## Overview ### Seizures Seizures caused by light are known as photosensitive epilepsy. Content that flickers, flashes, or blinks can trigger photosensitive epilepsy. Web technologies that use video, animated gifs, animated pngs, animated SVGs, Canvas, and CSS or JavaScript animations are all capable of content that can induce seizures or other incapacitating physical reactions. Certain visual patterns, especially stripes, can also cause physical reactions even though they are not animated. Photosensitive epilepsy is actually a kind of "reflex epilepsy"—seizures occurring in response to a trigger. In the case of photosensitive epilepsy, seizures are triggered specifically by flashing lights, but other types of reflex epilepsies may be triggered by the act of reading, or by noises. Patterns and images can also trigger epilepsy. The fact that static images may cause seizures and other disorders is documented in articles such as ["Gamma Oscillations and photosensitive epilepsy"](https://linkinghub.elsevier.com/retrieve/pii/S0960982217304062), where it is noted "_Certain visual images, even in the absence of motion or flicker, can trigger seizures in patients with photosensitive epilepsy_". The Epilepsy Foundation, in its article, ["Shedding Light on Photosensitivity, One of Epilepsy's Most Complex Conditions"](https://www.epilepsy.com/stories/shedding-light-photosensitivity-one-epilepsys-most-complex-conditions-0) talks about static images and patterns: "_Static or moving patterns of discernible light and dark stripes have the same effect as flashing lights because of the alternation of dark and bright areas."_ The Epilepsy Foundation of America Working Group is able to "quantify" the problem a little: _"A pattern with the potential for provoking seizures contains clearly discernible stripes, numbering more than five light-dark pairs of stripes in any orientation_". In addition to stripes, checkered patterns have also been known to cause photosensitive seizures, according to [Cedars-Sinai](https://www.cedars-sinai.org/health-library/diseases-and-conditions/p/photosensitive-seizures.html). Although static images are possible as triggers, they are less consistent. The trigger that is well established and strong is flashing/strobe lights. Dr. Selim Benbadis of USF's Comprehensive Epilepsy Program notes, _"The only thing that is really documented is flashing lights, which can trigger seizures in patients with photosensitive epilepsy. Only a few types of epilepsies are photosensitive though, and the vast majority of epilepsies are not."_ In addition to seizures brought about by photosensitivity, listening to certain pieces of music can also trigger what are called musicogenic seizures, although these types of seizures seem to be much more rare. For a great introduction on the topic of musicogenic seizures, visit Epilepsy Ontario's web page on [Musicogenic Seizures](https://epilepsyontario.org/musicogenic-seizures/). Seizures and epilepsy are not the same. In its article ["A Revised Definition of Epilepsy"](https://www.epilepsy.com/stories/revised-definition-epilepsy), the Epilepsy Foundation notes that "_a seizure is an event and epilepsy is the disease involving recurrent unprovoked seizures_." According to the Epilepsy Foundation's page ["How Serious Are Seizures?"](https://www.epilepsy.com/what-is-epilepsy/understanding-seizures/how-serious-are-seizures), _"Sudden unexpected death in epilepsy (SUDEP) is likely the most common disease-related cause of death in with epilepsy. It is not frequent but it is a very real problem and people need to be aware of its risk"_. The point is, seizures most definitely can be and are fatal, and developers and designers are incredibly important for making the web a safer place for those with sensitivities to photosensitive or musicogenic triggers. Seizures can be fatal, but even the ones that are "only" debilitating can be of such severity that they render the user incapacitated. Other disorders, such as disorientation, nausea, vomiting, and more can also be so severe that the user is unable to function. The Epilepsy Foundation's article, ["Photosensitivity and Seizures"](https://www.epilepsy.com/what-is-epilepsy/seizure-triggers/photosensitivity), provides a list of triggers that may cause seizures in photosensitive people; here's an excerpt from that list: - Television screens or computer monitors due to the flicker or rolling images. - Certain video games or TV broadcasts containing rapid flashes or alternating patterns of different colors. - Intense strobe lights like visual fire alarms. - Natural light, such as sunlight, especially when shimmering off water, flickering through trees or through the slats of Venetian blinds. - Certain visual patterns, especially stripes of contrasting colors. That same article continues that many factors must combine to trigger the photosensitive reaction. Of note is that it includes the wavelength of light as a possible factor; wavelengths in the red part of the spectrum seem to be especially problematic. In the article, ["Understanding WCAG 2.0 Three Flashes or Below Threshold"](https://www.w3.org/TR/UNDERSTANDING-WCAG20/seizure-does-not-violate.html) notes generally that: _"Individuals who have photosensitive seizure disorders can have a seizure triggered by content that flashes at certain frequencies for more than a few flashes"_ and goes on to note, very specifically that: "_People are even more sensitive to red flashing than to other colors, so a special test is provided for saturated red flashing_". You don't even need an image or video to cause harm. A {{HTMLElement('div')}} element set to change color and luminosity at high frequency, easily done via JavaScript, can cause real harm. And, flickering can occur everywhere. For example, "spinners" commonly used to display while pages load can easily "flicker" while spinning. Additional concerns exist for individuals with motor-skill problems. For example, the page for Trace Research & Development Center's [Photosensitive Epilepsy Analysis Tool](https://trace.umd.edu/peat/) notes that _"Photosensitive seizures can be provoked by certain types of flashing in web or computer content, including mouse-overs that cause large areas of the screen to rapidly flash on and off repeatedly"_. ### Other physical reactions Nausea, vertigo (or dizziness), and disorientation are very nonspecific symptoms associated with all kinds of diseases and not particularly suggestive of seizures (except maybe disorientation, which is seen in seizures). However, seizures are not the only adverse physical response possible from flashing, flickering, blinking, and other such stimuli. In 1997, a Japanese cartoon featured an animated "virus bomb". Some of the children watching the cartoon reacted by having seizures, others by suffering nausea, shaking, and vomiting blood. The reactions from the children were so severe, they had to be rushed to the emergency room. The physical disorders listed below are all possible consequences: each of these physical reactions may be so severe as to be incapacitating. - Seizures - Vestibular Disorders - Migraines - Nausea - Vomiting ## Flashing, blinking, & flickering Although "flashing" and "blinking" are sometimes used interchangeably, they are not the same. According to the W3C, blinking is a distraction problem, whereas flashing refers to content that occurs more than 3 times per second, and which is sufficiently large and bright. [Section 508](https://www.section508.gov/content/guide-accessible-web-design-development/#flashing) prohibits flickering effects with a frequency greater than 3 Hz (flickers per second) and lower than 55 Hz. The Epilepsy Foundation's article ["Shedding Light on Photosensitivity, One of Epilepsy's Most Complex Conditions"](https://www.epilepsy.com/stories/shedding-light-photosensitivity-one-epilepsys-most-complex-conditions-0) notes that _"Generally, flashing lights between the frequencies of five to 30 flashes per second (Hertz) are most likely to trigger seizures. In order to be safe, the consensus recommends that photosensitive individuals should not be exposed to flashes greater than three per second."_ For some people, however, flashing/blinking can cause symptoms at less than 3 Hz. It's important to note that not all flashing and blinking is bad. NASA, in its document titled, ["Blinking, Flashing, and Temporal Response"](https://colorusage.arc.nasa.gov/flashing.php) notes that blinking and flashing can be powerful tools for drawing attention—as is necessary for warning buttons (this assumes that users can still see the screen while elements are flashing, which is not always true). For some users, blinking buttons also caution that they must be used sparingly, and with care. As it applies to web design, systems that alert company employees to danger by "hijacking" the screen to provide a flashing warning of emergency need to take into consideration the rate, size, and luminosity changes on the screen as these warnings are flashed. ### Flashing and flickering—how is danger quantified? According to the article ["Photic- and pattern-induced seizures: expert consensus of the Epilepsy Foundation of America Working Group",](https://onlinelibrary.wiley.com/doi/epdf/10.1111/j.1528-1167.2005.31405.x) _"A flash is a potential hazard if it has luminance ≥20 cd/m<sup>2</sup>, occurs at a frequency of ≥3 Hz, and occupies a solid visual angle of ≥0.006 steradians (approximately 10% of the central visual field or 25% of screen area at typical viewing distances)."_ How far is a typical viewing distance? The recommendation considered for a typical viewing distance at the time of writing was "_the area can be taken as applying to an area >25% of the area of a television screen, assuming standard viewing distances of ≥2 m (∼9 feet)"_. Much has changed since that time, and we are now much closer to our screen. Certain colors, and/or combinations of colors, also matter. ["Certain Colors More Likely To Cause Epileptic Fits, Researchers Find"](https://www.sciencedaily.com/releases/2009/09/090925092858.htm) notes that _"…complexities underlying brain dynamics could be modulated by certain color combinations more than the others, for example, red-blue flickering stimulus causes larger cortical excitation than red-green or blue-green stimulus."_ ### Flashing & flashing red [WCAG 2.3.1 general flash and red flash thresholds](https://www.w3.org/WAI/WCAG21/Understanding/three-flashes-or-below-threshold.html) are defined as follows: - A **general flash** is defined as a pair of opposing changes in [relative luminance](https://www.w3.org/TR/WCAG21/#dfn-relative-luminance) of 10% or more of the maximum relative luminance where the relative luminance of the darker image is below 0.80, and where "a pair of opposing changes" is an increase followed by a decrease, or a decrease followed by an increase; - A **red flash** is defined as any pair of opposing transitions involving a saturated red. These standards are based on earlier research. In 2004, The Epilepsy Foundation of America convened a workshop developed a [consensus](https://pubmed.ncbi.nlm.nih.gov/16146438/) on photosensitive seizures, stating _"A flash is a potential hazard if it has luminance at least 20 cd/m<sup>2</sup>, occurs at a frequency of least 3 Hz, and occupies a solid visual angle of at least 0.006 steradians (about 10% of the central visual field or 25% of screen area at typical viewing distances)."_ The transition to or from a saturated red is important and constitutes a risk on its own: "_Irrespective of luminance, a transition to or from a saturated red is also considered a risk._" ### Size and distance #### How big? It depends "Relative" size and distance both matter. According to [PEAT](https://trace.umd.edu/peat/), _"The combined area of flashes occurring concurrently occupies no more than a total of one quarter of any 341 x 256 pixel rectangle anywhere on the displayed screen area when the content is viewed at 1024 by 768 pixels."_ The point that the field of vision is an important consideration arises in the article addressing WCAG 2.3.1 continues: "_The 1024 x 768 screen is used as the reference screen resolution for the evaluation. The 341 x 256 pixel block represents a 10 degree viewport at a typical viewing distance. (The 10 degree field is taken from the original specifications and represents the central vision portion of the eye, where people are most susceptible to photo stimuli.)_" This pixel area ratio calculates for relative size, but distance also matters. Distance matters because it affects the total field of vision. When viewers wear ocular masks for gaming, the field of vision is likely enveloped in its entirety by the screen. [WebVR](https://webvr.info/) is an open specification that makes it possible to experience VR in your browser, which can be experienced on phone, computer or headset. The concern about flashing images in an ocular mask is a growing one, since the mask is so close to the eyes. [The Epilepsy Society (UK)](https://epilepsysociety.org.uk/), in their article, ["3d Films and Virtual Reality"](https://epilepsysociety.org.uk/3d-films-and-virtual-reality#.XQlC5ohKiUk), noted: _"With VR the images flash very quickly and generally this is too quickly to trigger a seizure in people with photosensitive epilepsy. However, the field of view is large and so more of the eye is stimulated. This means that more of the brain may be affected and this may trigger a photosensitive seizure."_ (Note that some users will not be able to see with blinking cursors, and may get migraines, motion sickness, and disorientation, although blinking cursors occupy a much smaller area of the screen.) ### Patterns, and parallax Contrasting dark and light geometric patterns are a known culprit; stripes and checks are the best known examples. The Epilepsy Foundation of America Working Group lists how many light-dark pairs of stripes are likely to provoke seizures, and, in what conditions. If a pattern is unchanging and straight, eight lines is the maximum allowable, but if it undulates, no more than five lines. Parallax effects can cause disorientation. Use parallax effects with caution; if you must use them, ensure the user has a control to turn them off. "A pattern with the potential for provoking seizures contains clearly discernible stripes, numbering more than five light-dark pairs of stripes in any orientation. When the light-dark stripes of any pattern collectively subtend at the eye from the minimal-expected viewing distance a solid angle of >0.006 steradians, the luminance of the lightest stripe is >50 cd/m<sup>2</sup>, and the pattern is presented for ≥0.5 s, then the pattern should display no more than five light-dark pairs of stripes, if the stripes change direction, oscillate, flash, or reverse in contrast; if the pattern is unchanging or smoothly drifting in one direction, no more than eight stripes." Not all is known, and even with the metrics listed above, additional factors come into play. For example, going from a smaller area to a larger one increases the likelihood that the brain responds, as well as increasing contrast, and increasing spatial frequency from a low to middle. It's also known, although the reasoning is not understood behind it, that going from simple orientations (for example, stripes) to a multiple one (for example, the checkered pattern that emerges when laying one set of stripes on top of, but perpendicular to, the original set) affects the brain. ### Colors Understanding color is important for accessibility. See [understanding colors and luminance](/en-US/docs/Web/Accessibility/Understanding_Colors_and_Luminance) as it relates to web accessibility and accessibility in general. How the color relates to its background—usually framed in terms of contrast—and how drastically the color changes frame to frame in animation is important. For more on this, see [Three Flashes or Below Threshold Understanding SC 2.3.1](https://www.w3.org/TR/UNDERSTANDING-WCAG20/seizure-does-not-violate.html). #### The Special Case of Red It has been demonstrated that [some colors are more likely to cause epileptic fits than others](https://www.sciencedaily.com/releases/2009/09/090925092858.htm). Human physiology and psychology are affected by the color red in general. Its power to influence behavior has even been noted in animals. - **Red Desaturation tests:** The human eye is so sensitively tuned to red that ophthalmologists set up a test using it. The Red desaturation test assesses the integrity of the optic nerve. For more information as to how an ophthalmologist uses this test, see [Red Desaturation](https://www.smart-optometry.com/red-desaturation/). - **Red Environment:** Studies have shown that for those who suffer Traumatic Brain Injury, [cognitive function is reduced in a red environment](https://pubmed.ncbi.nlm.nih.gov/20649469/). [Saturated Red](/en-US/docs/Web/Accessibility/Understanding_Colors_and_Luminance) is a special, dangerous case, and there are special tests for it. In addition to a red environment affecting the cognitive function of those with Traumatic Brain Injury, color in the red spectrum wavelength seems to require special concern and special tests. Dr. Gregg Vanderheiden, when testing the Photosensitive Epilepsy Analysis Tool, noted that the seizure rates were much higher than expected. They found that we are much more sensitive to saturated red flashing. (See the video, [The Photosensitive Epilepsy Analysis Tool](https://www.pbs.org/video/university-place-the-photosensitive-epilepsy-analysis-tool-ep-429/).) #### Websafe does not mean seizure-safe Note that the color **#990000** is considered "**websafe**". That does _not_ mean it is "safe for not causing seizures", it only means that the color may be "safely" reproduced accurately by the technology used to generate color on screens. ## Measuring to prevent harm Measuring the potential for harm is a good starting point. Factors considered within tests include color, luminosity, size, contrast, and in cases of animation, frequency. WCAG 2.1 provides guidance for evaluating content. In August, 2004, the Epilepsy Foundation of America convened a workshop to begin to develop an expert consensus on photosensitive seizures. The following, expert, and authoritative information is from: [Photic- and pattern-induced seizures: expert consensus of the Epilepsy Foundation of America Working Group.](https://pubmed.ncbi.nlm.nih.gov/16146438/) > A flash is a potential hazard if it has luminance ≥20 cd/m<sup>2</sup>, occurs at a frequency of ≥3 Hz, and occupies a solid visual angle of ≥0.006 steradians (approximately 10% of the central visual field or 25% of screen area at typical viewing distances). A transition to or from saturated red also is considered a risk. A pattern with the potential for provoking seizures contains clearly discernible stripes, numbering more than five light-dark pairs of stripes in any orientation. When the light-dark stripes of any pattern collectively subtend at the eye from the minimal-expected viewing distance a solid angle of >0.006 steradians, the luminance of the lightest stripe is >50 cd/m2, and the pattern is presented for ≥0.5 s, then the pattern should display no more than five light-dark pairs of stripes, if the stripes change direction, oscillate, flash, or reverse in contrast; if the pattern is unchanging or smoothly drifting in one direction, no more than eight stripes. These principles are easier to apply in the case of fixed media, for example, a prerecorded TV show, which can be analyzed frame-by-frame, as compared with interactive media. The "cd/m<sup>2</sup>" refers to candela per square meter. So for the web developer, how does this relate to measurements for color, luminance, and saturation? The candela is a SI unit (International System of units) of luminous intensity. It's a photometric term, and photometry deals with the measurement of visible light as perceived by human eyes. Wikipedia's article on ["Candela per square metre"](https://en.wikipedia.org/wiki/Candela_per_square_metre) puts it in terms of what we are familiar with as developers: on a display device, and in the RGB space. This is helpful, because there's a specific standard assumed to be used on monitors, printers, and the Internet, and it is the **sRGB** (standard Red Green Blue). > As a measure of light emitted per unit area, this unit is frequently used to specify the brightness of a display device. The [sRGB](https://en.wikipedia.org/wiki/SRGB) spec for monitors targets 80 cd/m<sup>2</sup>.[<sup>\[3\]</sup>](https://en.wikipedia.org/wiki/Candela_per_square_metre#cite_note-3) Typically, calibrated monitors should have a brightness of 120 cd/m<sup>2</sup>. Most consumer desktop [liquid crystal displays](https://en.wikipedia.org/wiki/Liquid_crystal_display) have luminances of 200 to 300 cd/m<sup>2</sup>.[<sup>\[4\]</sup>](https://en.wikipedia.org/wiki/Candela_per_square_metre#cite_note-4) [High-definition televisions](https://en.wikipedia.org/wiki/High-definition_television) range from 450 to about 1500 cd/m<sup>2</sup>. The takeaway is that the **sRGB** color space is a common touch point between research, assessment tools, and developers, since it is easily converted from the commonly used Hex code. ### Human physiology and psychology as a consideration Many experts work to quantify and measure to the greatest extent possible the kinds of web content that can serve as triggers for seizures. That said, it can't be forgotten that color is as much about human perception in the brain as it is the measurement of light coming from a computer screen. In addition to the psychological variances, there are also physiological differences among us. There will be variances and nuances as to how a real human being perceives, and responds to, color and light. For example, Tom Jewett, Lecturer Emeritus of Computer Sciences at Cal State University Long Beach, notes the following concerning [lightness in the HSL color scale](https://colortutorial.design/hsb.html) _"…The distinction between levels of lightness is not actually linear as the HSL scale would imply; we are much more sensitive to changes in lighter values than to darker ones."_ It's important to understand that light and its measurements are linear, but human vision and human perception are not. Investigation and discussion is ongoing as to how to relate the machine measurement of light as it passes from a computer screen, through the distance to the human eye, filtered by human vision, and then manipulated through the human brain. Even age and sex can play a role. According to the Epilepsy Foundation's article, ["Shedding Light on Photosensitivity, One of Epilepsy's Most Complex Conditions"](https://www.epilepsy.com/stories/shedding-light-photosensitivity-one-epilepsys-most-complex-conditions-0), _"Children and adolescents are more prone than adults to have an abnormal response to light stimulation, and the first light-induced seizure almost always occurs before age 20"._ The article follows with this statistic: _"Girls (60 percent) are more often affected than boys (40 percent), although seizures are more frequent in boys because they are more likely to be playing video games. Video games often contain potentially provocative light stimulation"_. **User testing is very problematic**. Naturally, no one wants to subject a seizure-prone individual to user testing. It's dangerous. To that point, one of the most ethical thing that developers and designers can do is use tools that have been developed by experts in the field who have worked hand-in-hand with physicians to develop the tool. As of this writing, there are two commonly available tools that have been ethically and professionally developed by researchers and physicians for film/videos: **PEAT**, and the **Harding Test**. ### Photosensitive Epilepsy Analysis Tool (PEAT) The [Trace Research and Development Center](https://trace.umd.edu/) has set a gold standard for a [Photosensitive Epilepsy Analysis Tool](https://trace.umd.edu/peat/), and they've made a point to make it **_free_** to download. PEAT can help authors determine whether animations or video in their content are likely to cause seizures. Please note the restriction on its use: **_Use of PEAT to assess material commercially produced for television broadcast, film, home entertainment, or gaming industries is prohibited. Use the Harding Test or other tools for commercial purposes._** To get a free copy of the University of Maryland's Photosensitive Epilepsy Analysis Tool, visit the [Trace Research & Development Center](https://trace.umd.edu/). ![University of Maryland College of Information Studies Photosensitive Epilepsy Analysis Tool.](peatversion1pt6.png) ### The Harding Test As use of the PEAT tool is prohibited for commercial use, television programmers can use the Harding Test at [HardingTest.com](https://www.hardingtest.com/). The Harding Test is another gold standard. Television programmers in various countries must pass this test before being able to broadcast, so the group at [HardingTest.com](https://www.hardingtest.com/) provides both analysis and certification of video content. ![Harding Flash and Pattern Analyzer.](screen_shot_2019-06-20_at_11.16.17_am.png) ## Accessibility Solutions for Developers All animations are potentially dangerous. As designers and developers our responsibility is to ensure we do no harm either intentionally or unintentionally. If we must include something that has the potential to cause harm, it is vital to prevent users from accidentally encountering the harmful content, and to provide ways for users to prevent and control animations mitigating potential harm. ### What the web developer can do #### Do no harm [WCAG Guideline 2.3 Seizures and Physical Reactions](https://www.w3.org/WAI/standards-guidelines/wcag/new-in-21/) provides an overview: _"Do not design content in a way that is known to cause seizures or physical reactions"_. Don't include animation that a user cannot control. Don't design with patterns known to cause problems. If you must include a gif or png with flashing in it, record it in a video format instead so that controls are available to the user. Give the user the ability to avoid it, turn it off, or render it less harmful. #### Understand malice As a developer or designer, ask yourself if strobing content really needs to be on your webpage. Even if handled properly, there are those who may download offending content from your site and weaponize it. It is believed the first documented attempt at using computers to effect physical harm via animation began Saturday, March 22, 2008: The Epilepsy Foundation's website was hacked via posts with flashing images and links falsely claiming to be helpful. Users with vestibular disorders who were seeking help from the site were affected. A series of legal considerations are underway after journalist Kurt Eichenwald, a known epileptic, suffered a seizure after being sent an animated gif in December 2016: the flashing gif carried the message, _"You deserve a seizure for your posts"_. #### Control exposure, control access Controlling exposure to the page is key to ensuring that someone susceptible to seizures is not exposed to it accidentally. WCAG notes that a single object can make the entire page unusable. If you believe you may have an image or animation that may cause seizures, control access to it by first displaying a warning about the content, and then putting it in a location where the user must opt in to it, such as clicking a button, or ensuring that the link to the page has a distinct and obvious warning. Consider using metadata such as `<meta name="robots" content="noindex, nofollow">` so that the page is not indexed by search engines. #### Do Not Index, Do Not Follow By not indexing the page, the likelihood that users will stumble upon it via search will be reduced. ```html <html lang="en"> <head> <title>…</title> <meta name="robots" content="noindex, nofollow" /> </head> </html> ``` ### Animated GIFs All image types are potentially dangerous, however, animated gifs deserve special mention because of their ubiquity, and the fact that the animation speed is actually controlled within the GIF file itself. #### Detect if a GIF is animated - [npm's animated-gif-detector](https://www.npmjs.com/package/animated-gif-detector) allows for the ability to determine animate _as early as possible_ in a given HTTP request. - Zakirt provides a gist for [animated-gif-detect.js](https://gist.github.com/zakirt/faa4a58cec5a7505b10e3686a226f285) With animated GIFs, ensure animation is inactive until the user chooses to activate it. For example, the user must push a button or check a box in order to start the animation. **Resources for detecting and controlling animated GIFs include:** - [RunKit Animated GIF Detector](https://npm.runkit.com/animated-gif-detector) - [github.com/rubentd/gifplayer](https://github.com/rubentd/gifplayer), a jQuery plugin that will help you play and stop animated gifs on your website ### Videos As in the case of animated GIFs, the user must push a button or check a box in order to start the animation. There are many ways to do this, such as NOT adding the [`autoplay`](/en-US/docs/Web/API/HTMLMediaElement/autoplay) attribute to `<video controls>`, or setting {{CSSxRef('animation-play-state')}} to `paused` as an initial state. To see a powerful example of how this can actually work see the article by Kirupa, ["Toggling Animations On and Off"](https://www.kirupa.com/html5/toggling_animations_on_off.htm). Kirupa uses the `animation-play-state` in concert with {{CSSxRef('transition')}}, {{CSSxRef('transform')}}, and [`prefers-reduced-motion`](/en-US/docs/Web/CSS/@media/prefers-reduced-motion) to create a very accessible experience under the user's control. [`animation-play-state`](https://www.w3.org/TR/css-animations-1/#animation-play-state) is a CSS property that sets whether an animation is running or paused. ```css div { animation-play-state: paused; } ``` [`CSS Transitions`](https://www.w3.org/TR/css-transitions-1/) can be used to set the duration to zero for the initial stage of animation. ```css div { transition-duration: 0s; } ``` ### Ensure the user can also stop animations as well as start them A {{HTMLElement('video')}} element with no attributes will not play automatically, and will also have no controls. Ensure that you add the `controls` attribute to the video element so that the user can stop the video as well as start it. ```html <video controls> <source src="video.mp4" type="video/mp4" /> <source src="video.ogg" type="video/ogg" /> Your browser does not support the video tag. </video> ``` #### Programmatically ensure controls are available The `HTMLMediaElement.controls` property reflects the `controls` HTML attribute, which controls whether user interface controls for playing the media item will be displayed. ##### Video To ensure that a video has controls that a user can access, ensure that you add the word "controls" to HTML video and audio elements. `<video controls>` ```html <video controls> <source src="myVideo.mp4" type="video/mp4" /> <source src="myVideo.webm" type="video/webm" /> <p> Your browser doesn't support HTML video. Here is a <a href="myVideo.mp4">link to the video</a> instead. </p> </video> ``` ##### Audio Taking that same example and applying it to audio: `<audio controls>` ```html <audio controls> <source src="myAudio.ogg" type="audio/ogg" /> <source src="myAudio.mp3" type="audio/mpeg" /> <p> Your browser does not support the audio element. Here is a <a href="myAudio.mp3">link to the audio</a> instead. </p> </audio> ``` ##### Audio as part of Video Note that the audio in videos can be controlled by the `muted` content attribute, even though the content is within the {{HTMLElement('video')}} element rather than the {{HTMLElement('audio')}} element. This example is from the section on [muted media attribute](https://html.spec.whatwg.org/multipage/media.html#concept-media-muted) description from the HTML Living Standard. It explains that the video will autoplay quietly in the background until the user takes action to unmute the audio. ```html <video src="adverts.cgi?kind=video" controls autoplay loop muted></video> ``` ### Control speed This seems obvious, but because there are so many MIME types, the mechanisms for handling them varies greatly, and for that reason there's not a one-size-fits-all solution to the problem. This is further complicated by the fact that even how files are classified complicates how they should be handled. For example, the .gif file format is usually understood to be an image, but is also considered a video file format in some circles because of its ability to be animated. For a comprehensive listing of media types, please visit [IANA.org's page for Media Types](https://www.iana.org/assignments/media-types/media-types.xhtml). The methods for sniffing them out is not a casual exercise. You may be interested in following the [MIME Sniffing](https://mimesniff.spec.whatwg.org/) standard at whatwg.org. Just about every kind of image can be animated; how they are animated varies, and therefore, the control of the animation varies. #### Commonly animated file types - **Bitmap**: Animation - **Canvas**: MDN's tutorial on Canvas has a great section on [basic animations](/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations). `setInterval()` is a mainstay in Canvas animation, but it is also interesting to see how it interacts with screen refresh. See the article, ["Controlling fps with requestAnimationFrame?"](https://stackoverflow.com/questions/19764018/controlling-fps-with-requestanimationframe) in which they discuss the nuts and bolts of implementing `requestAnimationFrame` against the backdrop of screen refresh. - **GIFs (Raster)**: Tough to crack because control for their animation resides within the gif files themselves. For information about controlling the speed of gifs see W3C's ["G152: Setting animated gif images to stop blinking after n cycles (within 5 seconds)"](https://www.w3.org/TR/WCAG20-TECHS/G152.html). A great Stack Overflow article on the subject is, ["Can you control GIF animation with JavaScript?"](https://stackoverflow.com/questions/2385203/can-you-control-gif-animation-with-javascript) - **GIFV (Raster)**: Considered a variant, video version of GIF. The format is not standardized, and must reference a "real" video file (e.g. a .webm file) which must exist elsewhere. - **JPG (Raster)** - **MNG (Raster)**: Multiple-image Network Graphics is a graphics file format for animated images. Also considered by some to be a video format. - **PNG, APNG (Raster)**: Portable Network Graphics and Animated Portable Network Graphics may both be animated. - **SVGs (Vector)**: The MDN document, ["SVG: Scalable Vector Graphics"](/en-US/docs/Web/SVG), notes that _"SVG is a text-based open Web standard. It is explicitly designed to work with other web standards such as [CSS](/en-US/docs/Web/CSS), [DOM](/en-US/docs/Web/API/Document_Object_Model), and [SMIL](/en-US/docs/Web/SVG/SVG_animation_with_SMIL)."_ SVGs can be used as an image like in this example: `<img src="example.svg" alt="This is an image using a svg as a source">`. This means that SVG appearance and animation can be controlled through CSS keyframes and animations. For interaction with JavaScript, see the MDN documents on [SVG Interfaces](/en-US/docs/Web/API/Document_Object_Model#svg_interfaces) and [Applying SVG effects to HTML content](/en-US/docs/Web/SVG/Applying_SVG_effects_to_HTML_content). - **Voxel (Raster)**: Three-dimensional [voxel](https://en.wikipedia.org/wiki/Voxel) raster graphics are employed in video games, as well as in medical imaging. #### Text can also be animated Translations and transformations can animate text in a div, and do harm. Although it is experimental technology, [`CSSKeyframe.keyText`](/en-US/docs/Web/API/CSSKeyframeRule/keyText) is being developed. Moving text can induce seizures for the same reasons that moving images do, so avoid animating your text. It's a good idea to avoid using moving text anyhow, as many screen readers cannot read moving text and it's bad user experience even for those with no vision or vestibular issues. ### CSS for animation In the style sheet or within the {{HTMLElement('style')}} element, many options can combine together to create a powerful experience for the user. We've already mentioned the `animation` property earlier in this document. It's actually shorthand for all animation properties, including: - `animation-play-state` - `animation-duration` has a value of `<time>`; this is the duration an animation takes to complete one cycle. This may be specified in either seconds `(s)` or milliseconds `(ms)`. A default value of `0s` indicates no animation should occur. - `animation-timing-function` The animation property is already powerful on its own, but combined with other properties and queries such as `prefers-reduced-motion`, a powerful set of options can be set up for the user. Setting `animation-duration` and `transition-duration` properties to a short duration rather than setting them to `animation: none` and `transition: none`, enables a safeguard to prevent issues in any case there is a dependency on the animation to run. ### JavaScript animation JavaScript is often used to control {{HTMLElement('canvas')}} elements and SVGs. Most JavaScript code that applies to HTML video also applies to audio. `HTMLMediaElement.playbackRate` is used to implement user controls for the playback rate for both video and audio. A value of 1.0 is default and considered normal speed; a value of 0.5 is half the speed, a value of 2.0 is twice the speed. A negative number plays the video or audio backwards. Set the playback rate property: `HTMLMediaElement.playbackRate = playbackspeed`. [document.getAnimations()](/en-US/docs/Web/API/Document/getAnimations) is an experimental technology, and includes [CSS Animations](/en-US/docs/Web/CSS/CSS_animations), [CSS Transitions](/en-US/docs/Web/CSS/CSS_transitions), and [Web Animations](/en-US/docs/Web/API/Web_Animations_API). The MDN page on [Document.getAnimations()](/en-US/docs/Web/API/Document/getAnimations) provides the following code sample of how to slow down all animations on a page to half speed: ```js document.getAnimations().forEach((animation) => { animation.playbackRate *= 0.5; }); ``` #### Image sources for animation One of the easiest ways is to start with an image that is already in existence, using it as an image source, and then animating it. Remember, you can use GIFs, JPGs, PNGs, SVGs and other file types here as an image source, as long as they are allowed file types—and sizes—in your environment. SVGs are often not allowed, due to security concerns. The MDN document, [Basic animations](/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations), provides outstanding examples of this, using multiple image sources for the sun, earth, and moon, and using several canvas methods to control the speed and animation of the earth as it orbits around the sun, and the moon as it orbits around the earth. Use the codepen available with this tutorial to adjust `ctx.rotate` in the code to see how the animation is affected when changes are made. #### If you absolutely, positively must use a flashing animation… Make sure it has a control on it. Make sure it is turned off when the viewer first encounters it, and that a user must opt-in to see the animation. An example of a format that has no controls available to the user is a gif file. Animation speed is controlled within the gif image itself. Converting an animated gif to video enables controls to be put on the animation, and gives the user agency. There are many free online converters available for use, such as [EZGif](https://ezgif.com/) and [GIF to MP4](https://gif-2-mp4.com/). #### Set user expectations Give users a heads-up as to what will happen before they click on that link. Describe the animation that is to follow. See [WCAG 2.1 Success Criterion 3.2.5 Change on Request](https://www.w3.org/TR/WCAG21/#change-on-request). #### Keep it small If you absolutely positively must have flashing, keep it small. Generally speaking, limit the size of the flash to an area approximately 341 by 256 pixels or less. This pixel size assumes that a viewer is at a typical distance from the screen. As mentioned earlier, this size may be too big if the image is to be viewed at close range, such as in a VR headset. WebVR is an open specification that makes it possible to experience VR in your browser. WebVR can be experienced on phone, computer or headset. If you are designing for a game or VR that uses an ocular mask, **or CAN be used by an ocular mask**, such as in Firefox Reality (a browser for virtual reality), ensure that the size of the rectangle is much smaller than 341 by 256 pixels, because the image is much closer to a user's eyes. #### Reduce contrast Normally, higher contrast is a good thing when it comes to accessibility. The greater the contrast of a text color to its background (technically called _luminosity contrast ratio,_ according to W3.org's page on [Colors with Good Contrast](https://www.w3.org/WAI/perspective-videos/contrast/), the easier such content is to read. Users with low vision are especially appreciative of efforts to ensure high contrast of text against its background. When the content is animated, however, **_reducing_** contrast is actually a way to reduce the likelihood that the animated content will cause seizures. Drop the contrast ratio if three flashes within one second are detected. The contrast ratio is defined in [WCAG 2.1](https://www.w3.org/TR/WCAG21/) as follows: - _contrast ratio_ - : (L1 + 0.05) / (L2 + 0.05), where - L1 is the [relative luminance](https://www.w3.org/TR/WCAG21/#dfn-relative-luminance) of the lighter of the colors, and - L2 is the [relative luminance](https://www.w3.org/TR/WCAG21/#dfn-relative-luminance) of the darker of the colors. It's best if you can adjust the contrast before it is uploaded or published to the web. For videos and animated GIFS, the Adobe Suite of products is a phenomenal resource for traditional images. Also for images, an online tool available is pinetools.com's [Brightness and contrast online](https://pinetools.com/brightness-contrast-image). If you intend to make animated gifs, for example, start with one that has a lower contrast ratio. JavaScript is also an option for reducing contrast dynamically. Here's a code example from the section titled, ["Example: Setting the background color of a paragraph"](/en-US/docs/Web/API/Document_Object_Model/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces#setting_background_of_a_paragraph) from the MDN document, [Traversing an HTML table with JavaScript and DOM Interfaces](/en-US/docs/Web/API/Document_Object_Model/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces). Notice that the color in the example is described in the **RGB** color space. **HTML Content [(link to source page)](/en-US/docs/Web/API/Document_Object_Model/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces#html_content_2)** ```html <body> <input type="button" value="Set paragraph background color" onclick="set_background()" /> <p>hi</p> <p>hello</p> </body> ``` **JavaScript Content [(link to source page)](/en-US/docs/Web/API/Document_Object_Model/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces#javascript_content_2)** ```js function set_background() { // get a list of all the body elements (there will only be one), // and then select the zeroth (or first) such element myBody = document.getElementsByTagName("body")[0]; // now, get all the p elements that are descendants of the body myBodyElements = myBody.getElementsByTagName("p"); // get the second item of the list of p elements myP = myBodyElements[1]; myP.style.background = "rgb(255 0 0)"; } ``` #### Avoid fully saturated reds for flashing content As mentioned earlier in this document, the Epilepsy Foundation of America convened a workshop in August 2004 to begin to develop an expert consensus on photosensitive seizures. Among their results was the understanding that _"A flash is a potential hazard if it has luminance at least 20 cd/m2, occurs at a frequency of least 3 Hz, and occupies a solid visual angle of at least 0.006 steradians (about 10% of the central visual field or 25% of screen area at typical viewing distances). A transition to or from saturated red also is considered a risk."_ They also note in that same consensus: _"Irrespective of luminance, a transition to or from a saturated red is also considered a risk."_ ### Provide alternative CSS styles With the understanding that much of animation and flashing can be controlled via CSS methods, it's important to explore ways to make alternative options available to users, and to make the control of these options convenient and visible. #### Alternative Style Sheets Modern browsers will display the alternate CSS available in alternate style sheets if the users know where to look for them. In some cases, the alternate styles are revealed when the users go through the View menu, in other cases they are manifested in the settings, sometimes both. Not all users know to look for these options via the browser or settings, so it's worth considering doing things the old-fashioned way, with obvious buttons or links to change the style so that users can see them. Doing so won't conflict with, or override, the browser's ability to read the alternate style sheets, or the ability of the user to set preferences in the settings. It's important to know that certain users, such as those who rely on speech-recognition systems, often depend on legacy buttons and links because their disability prevents them from using a mouse, or to be able to take advantage of touch events on mobile tablets. Common ways to include the alternative stylesheets into your HTML documents are to use the {{HTMLElement('link')}} element, and {{CSSxref('@import')}}. #### The {{HTMLElement('link')}} element Use the {{HTMLElement('link')}} element, alongside with and together with the attributes of `rel="alternate stylesheet"` and for title, `title="…"` in the {{HTMLElement('head')}} section of the webpage. ```html <head> <title>Home Page</title> <link href="main.css" rel="stylesheet" title="Default Style" /> <link href="alternate1.css" rel="alternate stylesheet" title="Alternate One" /> <link href="alternate2.css" rel="alternate stylesheet" title="Alternate Two" /> </head> ``` **{{CSSxref('@import')}}** is also a way to incorporate style sheets, but it is not quite as well supported as the {{HTMLElement('link')}} element. ```html <style> @import url(alternate1.css); @import url(alternate2.css); </style> ``` By using alternate style sheets (remember to add the titles) you are setting it up for users to be able to use their browsers to choose alternate styles. ### Dynamic Style Switching One problem with relying on the browser to reveal alternative styles is that not all users are technically savvy enough to discover the alternate styles. Or, because of their disability, are not able to. Buttons or links make it obvious that options are available to many grateful users. There's a multitude of ways to add toggle buttons to allow the user to switch to the different style sheets. That said, the use of alternative style sheets are not the only option. Another option is to manipulate the style of the page itself. According to the MDN document, [Using dynamic styling information](/en-US/docs/Web/API/CSS_Object_Model/Using_dynamic_styling_information), _"where possible, it really is best practice to dynamically manipulate classes via the [`className`](/en-US/docs/Web/API/Element/className) property since the ultimate appearance of all of the styling hooks can be controlled in a single stylesheet"._ One of the best examples around as to how to do this is from the W3C's page, ["C29: Using a style switcher to provide a conforming alternate version"](https://www.w3.org/TR/WCAG20-TECHS/C29.html). ### Extreme Cases: Text-Only Alternatives A separate, alternative stylesheet that prevents images from being displayed is easy to make. It's a draconian solution; but it is one that is sometimes necessary for school teachers and other public servants who must serve those with extreme sensitivities. These public servants can ask their developers to develop a special alternative style sheet using `display: none`. Here's how to do it via CSS: ```css img { display: none; } ``` #### Take advantage of media queries with {{HTMLElement('style')}} In setting up media queries, you are enabling controls by the user; these controls are made available in the browser or in the OS. See the MDN document, [Accessibility: What users can do to browse more safely](/en-US/docs/Web/Accessibility/Accessibility:_What_users_can_to_to_browse_safely) to see more details of how a user accesses the controls. #### `prefers-reduced-motion` Support for `prefers-reduced-motion` in modern browsers is growing. ```css @media screen and (prefers-reduced-motion: reduce) { } @media screen and (prefers-reduced-motion) { } ``` To see a great example of how to use the code `prefers-reduced-motion`, visit the MDN document, [`prefers-reduced-motion`](/en-US/docs/Web/CSS/@media/prefers-reduced-motion), or see the example below from the section on ["New in Chrome 74"](https://developer.chrome.com/blog/new-in-chrome-74/). ```css button { animation: vibrate 0.3s linear infinite both; } @media (prefers-reduced-motion: reduce) { button { animation: none; } } ``` #### `prefers-color-scheme` This can be useful if the ambient light API is not available. Support is emerging. ```css @media (prefers-color-scheme: dark) { /* adjust styles for dark mode */ } ``` #### Window.matchMedia() There is a powerful tool available to developers via Window.matchMedia(). A great resource is MDN's document on [`Window.matchMedia()`](/en-US/docs/Web/API/Window/matchMedia). #### Media update feature The more often the screen is refreshed, the more stable it appears to the human eye, and the less it "flickers". The vast majority of modern technology refreshes at a rate that does not cause problems with photosensitivity. However, not everybody is wealthy enough to be able to afford the most recent technology: older or underpowered computers can have low refresh rates. [AbilityNet's Factsheet (November 2015) Computers and Epilepsy](https://www.abilitynet.org.uk/sites/abilitynet.org.uk/files/Epilepsy%20and%20Computing%20Nov%202015.pdf) describes more of the details on refresh rates. A very old article, Tech Republic's ["Epilepsy and CRT/LCD screen flicker"](https://www.techrepublic.com/forums/discussions/epilepsy-and-crt-lcd-screen-flicker/), had an interesting response concerning the refresh rates in Hz: - _"This effect is noticeable, and documented, up to 70 Hz."_ - _"These studies would seem to indicate that you should stay away from refresh rates under 70 Hz, and use a rate not divisible by 10."_ Eric Bailey, of CSS-Tricks, found an innovative use the update feature which, used in combination with animation-duration or transition-duration, to conclude at a rate that is imperceptible to the human eye. In other words, Eric's techniques address the refresh-rate problem. The CSS below is from the CSS-Tricks article, [" Revisiting prefers-reduced-motion, the reduced motion media query"](https://css-tricks.com/revisiting-prefers-reduced-motion/). ```css @media screen and (prefers-reduced-motion: reduce), (update: slow) { * { animation-duration: 0.001ms !important; animation-iteration-count: 1 !important; /* Hat tip Nick/cssremedy (https://css-tricks.com/revisiting-prefers-reduced-motion/#comment-1700170) */ transition-duration: 0.001ms !important; } } ``` From W3.org's page on [Media Queries 4](https://www.w3.org/TR/mediaqueries-4/): The `update` media feature is used to query the ability of the output device to modify the appearance of content once it has been rendered. It has the values of "none", "slow", and "fast". ## Developmental & Experimental Features ### MDN Navigator.doNotTrack [From the documentation](/en-US/docs/Web/API/Navigator/doNotTrack): _"Returns the user's do-not-track setting. This is "1" if the user has requested not to be tracked by websites, content, or advertising"_. ### Media Queries Level 5 EnvironmentMQ (Planned in Media Queries Level 5) - `light-level` - : [`light-level`](https://drafts.csswg.org/mediaqueries-5/#light-level) has three valid values: dim, normal, and washed. Interestingly, the specification refrains from actually defining the three levels in terms of a measurement of lux, because devices with a light sensor usually adjust the brightness of the screen automatically. The specifications also note the difference in technology, such as e-ink, which remains readable in bright daylight, versus liquid crystals, which do not. - `environment-blending` - : From W3C's Draft document, Media Queries Level 5: _"The [`environment-blending`](https://drafts.csswg.org/mediaqueries-5/#descdef-media-environment-blending) media feature is used to query the characteristics of the user's display so the author can adjust the style of the document. An author might choose to adjust the visuals and/or layout of the page depending on the display technology to increase the appeal or improve legibility."_ #### User Preference Media Features (Planned in Media Queries Level 5) [User Preference Media Features](https://drafts.csswg.org/mediaqueries-5/#mf-user-preferences) in [W3C Editor's Draft Media Queries Level 5](https://drafts.csswg.org/mediaqueries-5/) are especially promising in providing user control over media. Here are some highlights: - `inverted-colors` - : According to the section, [User Preference Media Features](https://drafts.csswg.org/mediaqueries-5/#mf-user-preferences), "The [`inverted-colors`](https://drafts.csswg.org/mediaqueries-5/#descdef-media-inverted-colors) media feature indicates whether the content is displayed normally, or whether colors have been inverted." - [`forced-colors`](https://drafts4.csswg.org/mediaqueries-5/#forced-colors) - : In [`forced-colors-mode`](https://drafts.csswg.org/css-color-adjust-1/#forced-colors-mode), the user agent enforces the user's preferred color palette on the page, overriding the author's chosen colors. From W3C's Draft document, Media Queries Level 5 section on forced-colors: _"The forced-colors media feature is used to detect if the user agent has enabled a [forced colors mode](https://drafts.csswg.org/css-color-adjust-1/#forced-colors-mode) where it enforces a user-chosen limited color palette on the page"._ The user will need to be made aware of this ability, and it will need to play nice with the appropriate value for the prefers-color-scheme media query. - `light-level` - : From W3C's Draft document, Media Queries Level 5 section on light-level: _"The [`light-level`](https://drafts.csswg.org/mediaqueries-5/#descdef-media-light-level) media feature is used to query about the ambient light-level in which the device is used, to allow the author to adjust style of the document in response."_ This will be a godsend to those who have motor-skills problems, or for some with cognitive difficulties, who cannot find the right "button" to change their screen settings. - prefers-contrast - : From W3C's Draft document, Media Queries Level 5 section on [`prefers-contrast`](https://drafts4.csswg.org/mediaqueries-5/#prefers-contrast): _"The `prefers-contrast` media feature is used to detect if the user has requested the system increase or decrease the amount of contrast between adjacent colors. For example, many users have difficulty reading text that has a small difference in contrast to the text background and would prefer a larger contrast."_ Sometimes there can be such a thing as too much contrast; a halo effect around text can occur in such situations and actually reduce legibility. Putting the amount of contrast in the user's control is a definite gift for accessibility. #### `MediaQueryList` Interface Section 4.2 from the CSSWG.org drafts integrates with the [event loop](https://html.spec.whatwg.org/multipage/webappapis.html#event-loop) defined in HTML. [HTML](https://drafts.csswg.org/cssom-view/#biblio-html) for the [`MediaQueryList`](https://drafts.csswg.org/cssom-view/#mediaquerylist) object. See the MDN document, [MediaQueryList](/en-US/docs/Web/API/MediaQueryList) for more information. #### Personalization Help and Support The requirement for the `literal` property is taken from [section 23 Non-literal Text and Images](https://www.w3.org/TR/personalization-semantics-help-1.0/). **Requirement:** Some users cannot understand non-literal text and icons such as metaphors, idioms etc. The `literal` property is intended to identify text or images as non-literal and allows the author to explain non-literal text and images to users. #### Transitions (for CSS and SVG) The following is from the [Web Animations model](https://www.w3.org/TR/web-animations-1/) CSSWG.org drafts The Web Animations model is intended to provide the features necessary for expressing [CSS Transitions](https://drafts.csswg.org/web-animations/#biblio-css-transitions-1), [CSS Animations](https://drafts.csswg.org/web-animations/#biblio-css-animations-1), and [SVG](https://drafts.csswg.org/web-animations/#biblio-svg11). ## See also ### MDN - [Accessibility: What users can do to browse more safely](/en-US/docs/Web/Accessibility/Accessibility:_What_users_can_to_to_browse_safely) - [Accessibility: Understanding color and luminance](/en-US/docs/Web/Accessibility/Understanding_Colors_and_Luminance) - [Applying SVG effects to HTML Content](/en-US/docs/Web/SVG/Applying_SVG_effects_to_HTML_content) - [Basic Animations](/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations) (Canvas Tutorial) - [Canvas API](/en-US/docs/Web/API/Canvas_API) - [CanvasRenderingContext2D.drawImage()](/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage) - [\<color>](/en-US/docs/Web/CSS/color_value) - [Document Object Model](/en-US/docs/Web/API/Document_Object_Model) - [MediaQueryList](/en-US/docs/Web/API/MediaQueryList) - [Using dynamic styling information](/en-US/docs/Web/API/CSS_Object_Model/Using_dynamic_styling_information) - [WebGL: 2D and 3D graphics for the web](/en-US/docs/Web/API/WebGL_API) - [WebVR API](/en-US/docs/Web/API/WebVR_API) ### Color - [Color Tutorial: describing color](https://colortutorial.design/) Tom Jewett - [Formula to Determine Brightness of RGB color](https://stackoverflow.com/questions/596216/formula-to-determine-perceived-brightness-of-rgb-color) Stack Exchange Discussion Thread - [How the Color Red Influences Our Behavior](https://www.scientificamerican.com/article/how-the-color-red-influences-our-behavior/) Scientific American By Susana Martinez-Conde, Stephen L. Macknik on November 1, 2014 ### Discussions - [Problems with WCAG 2.0 Flash Definition #553](https://github.com/w3c/wcag/issues/553) - [WCAG 2.1 Understanding 2.3.1 - missing/vague dimension definitions #585](https://github.com/w3c/wcag/issues/585) ### Epilepsy and Seizures - [Shedding Light on Photosensitivity, One of Epilepsy's Most Complex Conditions](https://www.epilepsy.com/stories/shedding-light-photosensitivity-one-epilepsys-most-complex-conditions-0) Epilepsy Foundation: _"Certain individuals are born with special sensitivity to flashing lights or contrasting visual patterns, such as stripes, grids and checkerboards. Because of this condition, their brain will produce seizure-like discharges when exposed to this type of visual stimulation."_ - [Gamma oscillations and photosensitive epilepsy](https://www.sciencedirect.com/science/article/pii/S0960982217304062?via%3Dihub) Current Biology [Volume 27, Issue 9](https://www.sciencedirect.com/journal/current-biology/vol/27/issue/9), 8 May 2017, Pages R336-R338: _"Certain [visual images](https://www.sciencedirect.com/topics/biochemistry-genetics-and-molecular-biology/retina-image), even in the absence of motion or flicker, can trigger seizures in patients with photosensitive epilepsy."_ - [Photosensitive Seizures. Cedars-Sinai](https://www.cedars-sinai.org/health-library/diseases-and-conditions/p/photosensitive-seizures.html) "_Photosensitive seizures are triggered by flashing or flickering lights. These seizures can also be triggered by certain patterns such as stripes._" - [Photic-and pattern-induced seizures: expert consensus of the Epilepsy Foundation of America Working Group](https://pubmed.ncbi.nlm.nih.gov/16146438/) Eplepsia 2005 Sept, 46(9):1423-5 PubMed.gov NCBI [Harding G](https://pubmed.ncbi.nlm.nih.gov/?term=Harding%20G%5BAuthor%5D&cauthor=true&cauthor_uid=16146438), [Wilkins AJ](https://pubmed.ncbi.nlm.nih.gov/?term=Wilkins%20AJ%5BAuthor%5D&cauthor=true&cauthor_uid=16146438), [Erba G](https://pubmed.ncbi.nlm.nih.gov/?term=Erba%20G%5BAuthor%5D&cauthor=true&cauthor_uid=16146438), [Barkley GL](https://pubmed.ncbi.nlm.nih.gov/?term=Barkley%20GL%5BAuthor%5D&cauthor=true&cauthor_uid=16146438), [Fisher RS](https://pubmed.ncbi.nlm.nih.gov/?term=Fisher%20RS%5BAuthor%5D&cauthor=true&cauthor_uid=16146438); [Epilepsy Foundation of America Working Group](https://pubmed.ncbi.nlm.nih.gov/?term=Epilepsy%20Foundation%20of%20America%20Working%20Group%5BCorporate%20Author%5D). ### GPII - [Accessibility Master List](https://ds.gpii.net/learn/accessibility-masterlist) Gregg Vanderheiden Ph.D. Editor ### Harding Along with the PEAT tool, is generally recognized to be one of the two "gold standards" for analyzing flashes. - [Harding Flash and Pattern Analyzer](https://www.hardingfpa.com) ### ISO - [IEC 61966-2-2:2003(en)](https://www.iso.org/obp/ui/#iso:std:iec:61966:-2-2:ed-1:v1:en) Multimedia systems and equipment — Colour measurement and management — Part 2-2: Colour management — Extended RGB color space — scRGB ### Photosensitive Epilepsy Analysis Tool Along with the Harding tool, is generally recognized to be one of the two "gold standards" for analyzing flashes. - [Trace Research and Development Center](https://trace.umd.edu/peat/) - [Using PEAT To Create Seizureless Web Animations](https://www.useragentman.com/blog/2017/04/02/using-peat-to-create-seizureless-web-animations/) ### W3C - [CSS Color Module Level 3](https://www.w3.org/TR/css-color-3/) - [Personalization Semantics Explainer 1.0](https://www.w3.org/TR/personalization-semantics-1.0/). Working Draft - [Personalization Tools 1.0](https://www.w3.org/TR/2019/WD-personalization-semantics-tools-1.0-20190711/) Working Draft - [Three Flashes or Below Threshold Understanding SC 2.3.1](https://www.w3.org/TR/UNDERSTANDING-WCAG20/seizure-does-not-violate.html) Understanding WCAG 2.0 (Older, but contains some explanations of references made in the WCAG 2.1 criteria) - [Three Flashes or Below Threshold Understanding Success Criterion 2.3.1](https://www.w3.org/WAI/WCAG21/Understanding/three-flashes-or-below-threshold.html) Understanding WCAG 2.1 - [Understanding Success Criteria 1.4.3: Contrast (Minimum)](https://www.w3.org/WAI/WCAG21/Understanding/contrast-minimum.html) - [Web Accessibility Initiative (WAI)](https://www.w3.org/WAI/) - [Web Animations Model](https://www.w3.org/TR/web-animations-1/) W3C Working Draft - [Web Content Accessibility Guidelines (WCAG) 2.0](https://www.w3.org/TR/WCAG20/#relativeluminancedef) definition of relative luminance - [Web Content Accessibility Guidelines (WCAG) 2.1](https://www.w3.org/TR/WCAG21/) ## Contributors Heartfelt thanks to Teal; Wayne Dick of the [Low Vision Task Force of the W3C](https://www.w3.org/WAI/GL/task-forces/low-vision-a11y-tf/); Tom Jewett and Eric Eggert from [Knowbility](https://knowbility.org/); Jim Allan of the [Diagram Center](https://diagramcenter.org/); and Dr. Selim R. Benbadis, Director, [Comprehensive Epilepsy Program and Clinical Neurophysiology Laboratory at USF and TGH in Tampa, Florida](https://health.usf.edu/medicine/neurology/epilepsy) for their great, great assistance and discussions on this topic. We are _all_ in tremendous gratitude to the Trace Research & Development Center for making their amazing tool, the [Photosensitive Epilepsy Analysis Tool (PEAT)](https://trace.umd.edu/peat/) for free.
0
data/mdn-content/files/en-us/web
data/mdn-content/files/en-us/web/webdriver/index.md
--- title: WebDriver slug: Web/WebDriver page-type: landing-page --- {{QuickLinksWithSubpages}} WebDriver is a remote control interface that enables introspection and control of user agents. It provides a platform- and language-neutral wire protocol as a way for out-of-process programs to remotely instruct the behavior of web browsers. To have the ability to write instruction sets that can be run interchangeably in many browsers on different platforms is critical to deliver a consistent experience to users. With the new wave of developments on the web platform, the increase diversity in devices and demands for real interoperability between the technologies, WebDriver provides tooling for [cross-browser testing](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Introduction). Provided is a set of interfaces to discover and manipulate DOM elements in web documents and to control the behavior of a user agent. It is primarily intended to allow web authors to write tests that automate a user agent from a separate controlling process, but may also be used in such a way as to allow in-browser scripts to control a — possibly separate — browser. ## Usage So what does WebDriver let you do and what does it look like? Since WebDriver is programming language neutral, the answer to this question depends on which WebDriver client you're using and the choice of language. But using a popular client written in Python, your interaction with WebDriver might look like this: ```python from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.expected_conditions import presence_of_element_located with webdriver.Firefox() as driver: driver.get("https://google.com/ncr") wait = WebDriverWait(driver, 10) driver.find_element(By.NAME, "q").send_keys("cheese" + Keys.RETURN) wait.until(presence_of_element_located((By.XPATH, '//*[@id="rcnt"]'))) results = driver.find_elements(By.XPATH, "//a[@href]") for i, elem in enumerate(results): print(f'#{i} {elem.text} ({elem.get_attribute("href")})') ``` This might produce output akin to this: ```plain #1 Cheese - Wikipedia (https://en.wikipedia.org/wiki/Cheese) ``` ## Reference ### Commands [Commands](/en-US/docs/Web/WebDriver/Commands) {{ListSubpages("/en-US/docs/Web/WebDriver/Commands")}} ### Types [Types](/en-US/docs/Web/WebDriver/Types) - [Error object](/en-US/docs/Web/WebDriver/Errors#payload) - [Timeouts object](/en-US/docs/Web/WebDriver/Timeouts) - [WebElement](/en-US/docs/Web/WebDriver/WebElement) - [WebWindow](/en-US/docs/Web/WebDriver/WebWindow) ### Capabilities [Capabilities](/en-US/docs/Web/WebDriver/Capabilities) {{ListSubpages("/en-US/docs/Web/WebDriver/Capabilities")}} ### Errors [Errors](/en-US/docs/Web/WebDriver/Errors) {{ListSubpages("/en-US/docs/Web/WebDriver/Errors")}} ## Specifications - [WebDriver](https://w3c.github.io/webdriver/) ## See also - [Cross browser testing](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing) - [Selenium documentation](https://www.selenium.dev/documentation/)
0
data/mdn-content/files/en-us/web/webdriver
data/mdn-content/files/en-us/web/webdriver/errors/index.md
--- title: WebDriver errors slug: Web/WebDriver/Errors page-type: landing-page --- {{QuickLinksWithSubpages}} Any WebDriver [command](/en-US/docs/Web/WebDriver/Commands) that is sent to might plausibly receive an error [response](/en-US/docs/Web/WebDriver/Response). An error is represented by an [HTTP response](/en-US/docs/Web/HTTP) with an [HTTP status code](/en-US/docs/Web/HTTP/Status) in the 4xx or 5xx range, and a JSON payload holding details of the error. ## Payload The **error object** is a JSON Object that bears three, and sometimes four, fields: - `error` - : Error type. - `message` - : Human-readable description of the nature of the error. - `stacktrace` - : Stacktrace report of the active stack frames at the time when the error occurred. - `data` (optional) - : Arbitrary and implementation-defined data that it can be useful to present the user with. Many drivers include the [user prompt](/en-US/docs/Web/API/Window/alert)'s text when encountering an [unexpected alert open](/en-US/docs/Web/WebDriver/Errors/UnexpectedAlertOpen) error. ## Example For example a [`GET`](/en-US/docs/Web/HTTP/Methods/GET) request to `/session/1234/url`, where `1234` is a bogus session, would return a response with the {{HTTPStatus(404, "404 Not Found")}} status and the following body: ```json { "value": { "error": "invalid session id", "message": "No active session with ID 1234", "stacktrace": "" } } ``` It is optional for the driver to annotate errors with additional error data. Notably, this is common when a user prompt, such as `window.alert`, has opened a modal dialog after execution of your previous WebDriver command request. Because both WebDriver and JavaScript execution is halted by such a dialog, we see an [unexpected alert open](/en-US/docs/Web/WebDriver/Errors/UnexpectedAlertOpen) error in the subsequent response: ```json { "value": { "error": "unexpected alert open", "message": "", "stacktrace": "", "data": { "text": "Message from window.alert" } } } ``` In most [clients](/en-US/docs/Web/WebDriver/Clients) the error would be represented by some sort of error _type_ or _object representation_. In Python it is represented as a [`WebDriverException`](https://www.selenium.dev/selenium/docs/api/py/common/selenium.common.exceptions.html), in Node.js as a [`WebDriverError`](https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/lib/error_exports_WebDriverError.html), and in Java also as a [`WebDriverException`](https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/WebDriverException.html). ## Table of errors | Error type | HTTP status code | Description | | ------------------------------------------------------------------------------------- | ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [element click intercepted](/en-US/docs/Web/WebDriver/Errors/ElementClickIntercepted) | {{HTTPStatus(400, "400 Bad Request")}} | The [Element Click](/en-US/docs/Web/WebDriver/ElementClick) [command](/en-US/docs/Web/WebDriver/Command) could not be completed because the [element](/en-US/docs/Web/WebDriver/WebElement) receiving the events is obscuring the element that was requested clicked. | | [element not interactable](/en-US/docs/Web/WebDriver/Errors/ElementNotInteractable) | {{HTTPStatus(400, "400 Bad Request")}} | A [command](/en-US/docs/Web/WebDriver/Command) could not be completed because the element is not pointer- or keyboard interactable. | | [insecure certificate](/en-US/docs/Web/WebDriver/Errors/InsecureCertificate) | {{HTTPStatus(400, "400 Bad Request")}} | Navigation caused the user agent to hit a certificate warning, which is usually the result of an expired or invalid TLS certificate. | | [invalid argument](/en-US/docs/Web/WebDriver/Errors/InvalidArgument) | {{HTTPStatus(400, "400 Bad Request")}} | The arguments passed to a [command](/en-US/docs/Web/WebDriver/Command) are either invalid or malformed. | | [invalid cookie domain](/en-US/docs/Web/WebDriver/Errors/InvalidCookieDomain) | {{HTTPStatus(400, "400 Bad Request")}} | An illegal attempt was made to set a cookie under a different domain than the current page. | | [invalid element state](/en-US/docs/Web/WebDriver/Errors/InvalidElementState) | {{HTTPStatus(400, "400 Bad Request")}} | A [command](/en-US/docs/Web/WebDriver/Command) could not be completed because the element is in an invalid state, e.g. attempting to [clear](/en-US/docs/Web/WebDriver/ElementClear) an element that isn't both editable and resettable. | | [invalid selector](/en-US/docs/Web/WebDriver/Errors/InvalidSelector) | {{HTTPStatus(400, "400 Bad Request")}} | An element retrieval command provided an unknown selector strategy. | | [invalid session id](/en-US/docs/Web/WebDriver/Errors/InvalidSessionID) | {{HTTPStatus(404, "404 Not Found")}} | Given session ID is not recognized, meaning the session either does not exist of that it's not active. Note that a session that [has been deleted](/en-US/docs/Web/WebDriver/DeleteSession) cannot be re-used. | | [JavaScript error](/en-US/docs/Web/WebDriver/Errors/JavaScriptError) | {{HTTPStatus(500, "500 Internal Server Error")}} | An error occurred while executing JavaScript supplied by the user. | | [move target out of bounds](/en-US/docs/Web/WebDriver/Errors/MoveTargetOutOfBounds) | {{HTTPStatus(500, "500 Internal Server Error")}} | The target for mouse interaction is not in the browser's viewport and cannot be brought into that viewport. | | [no such alert](/en-US/docs/Web/WebDriver/Errors/NoSuchAlert) | {{HTTPStatus(404, "404 Not Found")}} | An attempt was made to operate on a user prompt when one was not open. | | [no such cookie](/en-US/docs/Web/WebDriver/Errors/NoSuchCookie) | {{HTTPStatus(404, "404 Not Found")}} | No cookie matching the given path name was found amongst the [cookies](/en-US/docs/Glossary/Cookie) of the current [document](/en-US/docs/Web/API/Document). | | [no such element](/en-US/docs/Web/WebDriver/Errors/NoSuchElement) | {{HTTPStatus(404, "404 Not Found")}} | An element could not be located on the page using the given search parameters. | | [no such frame](/en-US/docs/Web/WebDriver/Errors/NoSuchFrame) | {{HTTPStatus(404, "404 Not Found")}} | A [command](/en-US/docs/Web/WebDriver/Command) to switch to a frame could not be satisfied because the frame could not be found. | | [no such window](/en-US/docs/Web/WebDriver/Errors/NoSuchWindow) | {{HTTPStatus(404, "404 Not Found")}} | A [command](/en-US/docs/Web/WebDriver/Command) to switch to a window could not be satisfied because the window could not be found. | | [script timeout](/en-US/docs/Web/WebDriver/Errors/ScriptTimeout) | {{HTTPStatus(408, "408 Request Timeout")}} | A script did not complete before its timeout expired. | | [session not created](/en-US/docs/Web/WebDriver/Errors/SessionNotCreated) | {{HTTPStatus(500, "500 Internal Server Error")}} | A new session could not be created, either because the browser could not be started or because the provided [capabilities](/en-US/docs/Web/WebDriver/Capabilities) to start the session did not match. | | [stale element reference](/en-US/docs/Web/WebDriver/Errors/StaleElementReference) | {{HTTPStatus(404, "404 Not Found")}} | A [command](/en-US/docs/Web/WebDriver/Command) failed because the referenced [element](/en-US/docs/Web/WebDriver/WebElement) is no longer attached to the DOM. | | [timeout](/en-US/docs/Web/WebDriver/Errors/Timeout) | {{HTTPStatus(408, "408 Request Timeout")}} | An operation did not complete before its timeout expired. | | [unable to set cookie](/en-US/docs/Web/WebDriver/Errors/UnableToSetCookie) | {{HTTPStatus(500, "500 Internal Server Error")}} | A [command](/en-US/docs/Web/WebDriver/Command) to set a cookie's value could not be satisfied. | | [unable to capture screen](/en-US/docs/Web/WebDriver/Errors/UnableToCaptureScreen) | {{HTTPStatus(500, "500 Internal Server Error")}} | A screen capture was made impossible. | | [unexpected alert open](/en-US/docs/Web/WebDriver/Errors/UnexpectedAlertOpen) | {{HTTPStatus(500, "500 Internal Server Error")}} | A modal dialog was open, blocking this operation. | | [unknown command](/en-US/docs/Web/WebDriver/Errors/UnknownCommand) | {{HTTPStatus(404, "404 Not Found")}} | A [command](/en-US/docs/Web/WebDriver/Command) could not be executed because the driver was unaware of it. | | [unknown error](/en-US/docs/Web/WebDriver/Errors/UnknownError) | {{HTTPStatus(500, "500 Internal Server Error")}} | An unknown error occurred in the driver whilst processing the [command](/en-US/docs/Web/WebDriver/Command). | | [unknown method](/en-US/docs/Web/WebDriver/Errors/UnknownMethod) | {{HTTPStatus(405, "405 Method Not Allowed")}} | The requested [command](/en-US/docs/Web/WebDriver/Command) matched a known URL but did not match a method for that URL. | | [unsupported operation](/en-US/docs/Web/WebDriver/Errors/UnsupportedOperation) | {{HTTPStatus(500, "500 Internal Server Error")}} | Indicates that a [command](/en-US/docs/Web/WebDriver/Command) that should have executed properly cannot be supported for some reason. | ## See also - [WebDriver responses](/en-US/docs/Web/WebDriver/Response) - [WebDriver commands](/en-US/docs/Web/WebDriver/Commands)
0
data/mdn-content/files/en-us/web/webdriver/errors
data/mdn-content/files/en-us/web/webdriver/errors/unknowncommand/index.md
--- title: Unknown command slug: Web/WebDriver/Errors/UnknownCommand page-type: webdriver-error --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Errors")}} The **unknown command** error is a [WebDriver error](/en-US/docs/Web/WebDriver/Errors) that occurs when the driver does not recognize the command/HTTP endpoint. ## Examples The `/session/{session id}/foo` endpoint does not exist, and will return an unknown command error with a [`404 Not Found`](/en-US/docs/Web/HTTP/Status/404) HTTP status code: ```bash curl -i -d '{}' http://localhost:4444/session/foo ``` ```http HTTP/1.1 404 Not Found Connection: close Content-Type: application/json; charset=utf-8 Cache-Control: no-cache Content-Length: 113 Date: Fri, 30 Mar 2018 15:30:51 GMT {"value":{"error":"unknown command","message":"POST /session/asd did not match a known command","stacktrace":""}} ``` ## See also - [List of WebDriver errors](/en-US/docs/Web/WebDriver/Errors) - [List of WebDriver commands](/en-US/docs/Web/WebDriver/Commands)
0
data/mdn-content/files/en-us/web/webdriver/errors
data/mdn-content/files/en-us/web/webdriver/errors/javascripterror/index.md
--- title: JavaScript error slug: Web/WebDriver/Errors/JavaScriptError page-type: webdriver-error --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Errors")}} The **JavaScript** error is a [WebDriver error](/en-US/docs/Web/WebDriver/Errors) that occurs when a script the supplied by the user fails to execute. The underlying cause of the execution error is often supplied in the error message, along with a stacktrace provided by the JavaScript engine in the browser. ## Example Consider the following injected script which tries to use an undefined variable. In JavaScript this normally causes a ReferenceError to be thrown. WebDriver catches this error and serializes it as a JavaScript error: ```python from selenium import webdriver from selenium.common import exceptions session = webdriver.Firefox() try: session.execute_script("return foo") except exceptions.JavascriptException as e: print(e.message) ``` Output: ```plain JavascriptException: ReferenceError: foo is not defined ``` ## See also - [List of WebDriver errors](/en-US/docs/Web/WebDriver/Errors) - Associated commands: - [Execute Script](/en-US/docs/Web/WebDriver/Commands/ExecuteScript) - [Execute Async Script](/en-US/docs/Web/WebDriver/Commands/ExecuteAsyncScript)
0
data/mdn-content/files/en-us/web/webdriver/errors
data/mdn-content/files/en-us/web/webdriver/errors/staleelementreference/index.md
--- title: Stale element reference slug: Web/WebDriver/Errors/StaleElementReference page-type: webdriver-error --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Errors")}} The **stale element reference** error is a [WebDriver error](/en-US/docs/Web/WebDriver/Errors) that occurs because the referenced [web element](/en-US/docs/Web/WebDriver/WebElement) is no longer attached to the [DOM](/en-US/docs/Glossary/DOM). Every DOM element is represented in WebDriver by a unique identifying reference, known as a _[web element](/en-US/docs/Web/WebDriver/WebElement)_. The web element reference is a {{Glossary("UUID")}} used to execute commands targeting specific elements, such as [getting an element's tag name](/en-US/docs/Web/WebDriver/Commands/GetElementTagName) and [retrieving a property](/en-US/docs/Web/WebDriver/Commands/GetElementProperty) off an element. When an element is no longer attached to the DOM, i.e. it has been removed from the document or the document has changed, it is said to be _stale_. Staleness occurs for example when you have a web element reference and the document it was retrieved from navigates. ## Examples ### Document navigation Upon navigation, all web element references to the previous document will be discarded along with the document. This will cause any subsequent interaction with the [web element](/en-US/docs/Web/WebDriver/WebElement) to fail with the stale element reference error: ```python import urllib from selenium import webdriver from selenium.common import exceptions def inline(doc): return "data:text/html;charset=utf-8,{}".format(urllib.quote(doc)) session = webdriver.Firefox() session.get(inline("<strong>foo</strong>")) foo = session.find_element_by_css_selector("strong") session.get(inline("<i>bar</i>")) try: foo.tag_name except exceptions.StaleElementReferenceException as e: print(e) ``` Output: ```plain StaleElementReferenceException: The element reference of e75a1764-ff73-40fa-93c1-08cb90394b65 is stale either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed ``` ### Node removal When a document node is removed from the DOM, its web element reference will be invalidated. This will also cause any subsequent interaction with the [web element](/en-US/docs/Web/WebDriver/WebElement) to fail with the stale element reference error: ```python import urllib from selenium import webdriver from selenium.common import exceptions def inline(doc): return "data:text/html;charset=utf-8,{}".format(urllib.quote(doc)) session = webdriver.Firefox() session.get(inline("<button>foo</button>")) button = session.find_element_by_css_selector("button") session.execute_script(""" let [button] = arguments; button.remove(); """, script_args=(button,)) try: button.click() except exceptions.StaleElementReferenceException as e: print(e) ``` Output: ```plain StaleElementReferenceException: The element reference of e75a1764-ff73-40fa-93c1-08cb90394b65 is stale either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed ``` ## See also - [WebElement](/en-US/docs/Web/WebDriver/WebElement) - Associated commands: - [Find Element](/en-US/docs/Web/WebDriver/Commands/FindElement) - [Find Elements](/en-US/docs/Web/WebDriver/Commands/FindElements) - [Find Element From Element](/en-US/docs/Web/WebDriver/Commands/FindElementFromElement) - [Find Elements From Element](/en-US/docs/Web/WebDriver/Commands/FindElementsFromElement)
0
data/mdn-content/files/en-us/web/webdriver/errors
data/mdn-content/files/en-us/web/webdriver/errors/scripttimeout/index.md
--- title: Script timeout slug: Web/WebDriver/Errors/ScriptTimeout page-type: webdriver-error --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Errors")}} The **script timeout** error is a [WebDriver error](/en-US/docs/Web/WebDriver/Errors) that occurs when a script the user has provided did not complete before the session's [script timeout](/en-US/docs/Web/WebDriver/Errors/ScriptTimeout) duration expired. The script timeout duration is a configurable capability, which means you can change how long it will take before the driver interrupts an injected script. The driver will by default wait 30 seconds before interrupting the script and returning with a script timeout error, but this can be both extended, limited, and be set to indefinite. If the session script timeout duration is set to indefinite by using a `null` value, you are at risk of putting the session into a non-recoverable state. Be aware that this should be used with caution. ## Example Consider the following asynchronous script that will resolve the promise, or invoke the callback, after 35 seconds have passed: ```python from selenium import webdriver from selenium.common import exceptions session = webdriver.Firefox() try: session.execute_script(""" let [resolve] = arguments; setTimeout(resolve, 35000); """) except exceptions.ScriptTimeoutException as e: print(e.message) ``` Output: ```plain ScriptTimeoutException: Timed out after 35000 ms ``` However, it is possible to _extend_ the session's default script timeout by using capabilities if you have a script that you expect will take longer: ```python from selenium import webdriver from selenium.common import exceptions session = webdriver.Firefox(capabilities={"alwaysMatch": {"timeouts": {"script": 150000}}}) session.execute_script(""" let [resolve] = arguments; setTimeout(resolve, 35000); """) print("finished successfully") ``` Output: ```plain finished successfully ``` ## See also - [List of WebDriver errors](/en-US/docs/Web/WebDriver/Errors) - Associated commands and types: - [JavaScript error](/en-US/docs/Web/WebDriver/Errors/JavaScriptError) - [Execute Script](/en-US/docs/Web/WebDriver/Commands/ExecuteScript) - [Execute Async Script](/en-US/docs/Web/WebDriver/Commands/ExecuteAsyncScript)
0
data/mdn-content/files/en-us/web/webdriver/errors
data/mdn-content/files/en-us/web/webdriver/errors/invalidcookiedomain/index.md
--- title: Invalid cookie domain slug: Web/WebDriver/Errors/InvalidCookieDomain page-type: webdriver-error --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Errors")}} The **invalid cookie domain** error is a [WebDriver error](/en-US/docs/Web/WebDriver/Errors) that occurs when an illegal attempt was made to set a [cookie](/en-US/docs/Glossary/Cookie) under a different [domain](/en-US/docs/Glossary/Domain) than that of the current document. In WebDriver it is not permissible to set cookies for other domains than the domain of the [current browsing context](/en-US/docs/Glossary/Browsing_context)'s [document](/en-US/docs/Web/API/Document)'s domain. This error will also happen if the document is _cookie-averse_, that is if the document is not loaded via `http://`, `https://`, or `ftp://`. ## Example ### Other domains If the current domain were to be `example.com`, it would not be possible to [add a cookie](/en-US/docs/Web/WebDriver/Commands/AddCookie) for the domain `example.org`: ```python from selenium import webdriver from selenium.common import exceptions session = webdriver.Firefox() session.get("https://example.com/") try: cookie = {"name": "foo", "value": "bar", "domain": "example.org"} session.add_cookie(cookie) except exceptions.InvalidCookieDomainException as e: print(e.message) ``` Output: ```plain InvalidCookieDomainException: https://example.org/ ``` ### Cookie-averse documents This error may also occur when you visit a cookie-averse document, such as a file on your local disk: ```python from selenium import webdriver from selenium.common import exceptions session = webdriver.Firefox() session.get("file:///home/jdoe/document.html") try: foo_cookie = {"name": "foo", "value": "bar"} session.add_cookie(foo_cookie) except exceptions.InvalidCookieDomainException as e: print(e.message) ``` Output: ```plain InvalidCookieDomainException: Document is cookie-averse ``` ## See also - [List of WebDriver errors](/en-US/docs/Web/WebDriver/Errors) - Relevant WebDriver commands: - [Add Cookie](/en-US/docs/Web/WebDriver/Commands/AddCookie) - [Delete Cookie](/en-US/docs/Web/WebDriver/Commands/DeleteCookie) - [Delete All Cookies](/en-US/docs/Web/WebDriver/Commands/DeleteAllCookies) - [Get All Cookies](/en-US/docs/Web/WebDriver/Commands/GetAllCookies) - [Get Named Cookie](/en-US/docs/Web/WebDriver/Commands/GetNamedCookie)
0
data/mdn-content/files/en-us/web/webdriver/errors
data/mdn-content/files/en-us/web/webdriver/errors/unknownmethod/index.md
--- title: Unknown method slug: Web/WebDriver/Errors/UnknownMethod page-type: webdriver-error --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Errors")}} The **unknown method** error is a [WebDriver error](/en-US/docs/Web/WebDriver/Errors) that occurs when the driver does not recognize the [HTTP request method](/en-US/docs/Web/HTTP/Methods) used for the endpoint. WebDriver provides a largely REST-ish API and not all endpoints in this API has `GET`, `POST`, and `DELETE` methods. This error occurs when you try to call an endpoint with an HTTP request method it does not support. ## Examples The New Session command provides a `POST` request endpoint which lets you create new WebDriver sessions: ```bash % curl -d '{}' http://localhost:4444/session {"sessionId":"d4605710-5a4e-4d64-a52a-778bb0c31e00","value":{"XULappId":"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}","acceptSslCerts":false,"appBuildId":"20160913030425","browserName":"firefox","browserVersion":"51.0a1","command_id":1,"platform":"LINUX","platformName":"linux","platformVersion":"4.9.0-1-amd64","processId":17474,"proxy":{},"raisesAccessibilityExceptions":false,"rotatable":false,"specificationLevel":0,"takesElementScreenshot":true,"takesScreenshot":true,"version":"51.0a1"}} ``` It also implements the `DELETE` method for ending a session: ```bash % curl -X DELETE http://localhost:4444/session/d4605710-5a4e-4d64-a52a-778bb0c31e00 {} ``` But it does not, for example, provide a `GET` method, and this will consequently return an unknown method error: ```bash % curl http://localhost:4444/session/650f9df3-740e-314c-958d-307e41752fae {"value":{"error":"unknown command","message":"GET /session/650f9df3-740e-314c-958d-307e41752fae did not match a known command","stacktrace":""}}% ``` ## See also - [List of WebDriver errors](/en-US/docs/Web/WebDriver/Errors) - [List of WebDriver commands](/en-US/docs/Web/WebDriver/Commands)
0
data/mdn-content/files/en-us/web/webdriver/errors
data/mdn-content/files/en-us/web/webdriver/errors/invalidselector/index.md
--- title: Invalid selector slug: Web/WebDriver/Errors/InvalidSelector page-type: webdriver-error --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Errors")}} The **invalid selector** error is a [WebDriver error](/en-US/docs/Web/WebDriver/Errors) that occurs when an element retrieval command is used with an unknown [web element](/en-US/docs/Web/WebDriver/WebElement) selector strategy. The available selector strategies are [CSS](/en-US/docs/Web/WebDriver/WebElement#css-selector), [link text](/en-US/docs/Web/WebDriver/WebElement#link-text-selector), [partial link text](/en-US/docs/Web/WebDriver/WebElement#partial-link-text-selector), [tag name](/en-US/docs/Web/WebDriver/WebElement#tag-name-selector), and [XPath](/en-US/docs/Web/WebDriver/WebElement#tag-name-selector). Any other selector strategy is rejected with this error. ## See also - [List of WebDriver errors](/en-US/docs/Web/WebDriver/Errors) - [WebElement](/en-US/docs/Web/WebDriver/WebElement) - Element retrieval commands: - [Find Element](/en-US/docs/Web/WebDriver/Commands/FindElement) - [Find Elements](/en-US/docs/Web/WebDriver/Commands/FindElements) - [Find Element From Element](/en-US/docs/Web/WebDriver/Commands/FindElementFromElement) - [Find Elements From Element](/en-US/docs/Web/WebDriver/Commands/FindElementsFromElement)
0
data/mdn-content/files/en-us/web/webdriver/errors
data/mdn-content/files/en-us/web/webdriver/errors/invalidsessionid/index.md
--- title: Invalid session ID slug: Web/WebDriver/Errors/InvalidSessionID page-type: webdriver-error --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Errors")}} The **invalid session ID** error is a [WebDriver error](/en-US/docs/Web/WebDriver/Errors) that occurs when the server does not recognize the unique session identifier. This happens if the [session has been deleted](/en-US/docs/Web/WebDriver/Commands/DeleteSession) or if the session ID is invalid. ## Example ### Explicit session deletion A WebDriver session is explicitly deleted when quitting: ```python from selenium import webdriver from selenium.common import exceptions session = webdriver.Firefox() print("Current session is {}".format(session.session_id)) session.quit() try: session.get("https://mozilla.org") except exceptions.InvalidSessionIdException as e: print(e.message) ``` Output: ```plain Current session is 46197c16-8373-469b-bc56-4c4d9e4132b4 No active session with ID 46197c16-8373-469b-bc56-4c4d9e4132b4 ``` ### Implicit session deletion The session can also be _implicitly deleted_ if you close the last window or tab: ```python from selenium import webdriver from selenium.common import exceptions session = webdriver.Firefox() print("Current session is {}".format(session.session_id)) # closes current window/tab session.close() try: session.get("https://mozilla.org") except exceptions.InvalidSessionIdException as e: print(e.message) ``` Output: ```plain Current session is 46197c16-8373-469b-bc56-4c4d9e4132b4 No active session with ID 46197c16-8373-469b-bc56-4c4d9e4132b4 ``` ## See also - [List of WebDriver errors](/en-US/docs/Web/WebDriver/Errors) - [Session not created](/en-US/docs/Web/WebDriver/Errors/SessionNotCreated) - Related WebDriver commands: - [New Session](/en-US/docs/Web/WebDriver/Commands/NewSession) - [Delete Session](/en-US/docs/Web/WebDriver/Commands/DeleteSession)
0
data/mdn-content/files/en-us/web/webdriver/errors
data/mdn-content/files/en-us/web/webdriver/errors/invalidargument/index.md
--- title: Invalid argument slug: Web/WebDriver/Errors/InvalidArgument page-type: webdriver-error --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Errors")}} The **invalid argument** error is a [WebDriver error](/en-US/docs/Web/WebDriver/Errors) that occurs when the arguments passed to a [command](/en-US/docs/Web/WebDriver/Commands) are either invalid or malformed. Invalid argument errors can be likened to [`TypeError`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError)s in [JavaScript](/en-US/docs/Web/JavaScript), in that they can occur for a great many APIs when the input value is not of the expected type or malformed in some way. See the type- and bounds constraints for each [WebDriver command](/en-US/docs/Web/WebDriver/Commands). ## Example It is for example not possible to set a window size to a negative value: ```python from selenium import webdriver from selenium.common import exceptions session = webdriver.Firefox() try: session.set_window_size(-100, 0) except exceptions.InvalidArgumentException as e: print(e.message) ``` Output: ```plain InvalidArgumentException: Expected -100 to be >= 0 ``` ## See also - [List of WebDriver errors](/en-US/docs/Web/WebDriver/Errors) - [List of WebDriver commands](/en-US/docs/Web/WebDriver/Commands)
0
data/mdn-content/files/en-us/web/webdriver/errors
data/mdn-content/files/en-us/web/webdriver/errors/unknownerror/index.md
--- title: Unknown error slug: Web/WebDriver/Errors/UnknownError page-type: webdriver-error --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Errors")}} The **unknown element** error is a [WebDriver error](/en-US/docs/Web/WebDriver/Errors) that occurs when an unspecified error occurs in the driver whilst processing a [command](/en-US/docs/Web/WebDriver/Commands). An unknown error will usually be specific to a particular driver, so it's a good idea to read the error message, if any, for an indication of what happened. ## See also - [List of WebDriver errors](/en-US/docs/Web/WebDriver/Errors) - [List of WebDriver commands](/en-US/docs/Web/WebDriver/Commands)
0
data/mdn-content/files/en-us/web/webdriver/errors
data/mdn-content/files/en-us/web/webdriver/errors/insecurecertificate/index.md
--- title: Insecure certificate slug: Web/WebDriver/Errors/InsecureCertificate page-type: webdriver-error --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Errors")}} The **insecure certificate** error is a [WebDriver error](/en-US/docs/Web/WebDriver/Errors) that occurs when the remotely controlled browser hits a certificate warning of any kind. This is usually the result of [navigating](/en-US/docs/Web/WebDriver/Commands/NavigateTo) to a website with an expired or invalid [TLS certificate](/en-US/docs/Glossary/TLS). Examples of invalid certificates include self-signed, revoked, and cryptographically insecure certificates. Web browsers prevent and block traffic to domains with broken certificates since the communication with the server would be compromised. It is strongly recommended to fix the certificate situation instead of disabling certificate checks, even in test environments. WebDriver does offer an [`acceptInsecureCerts` capability](/en-US/docs/Web/WebDriver/Capabilities/acceptInsecureCerts) for disabling certificate checks for the length of the session's duration, but it is important to emphasize that its use is highly discouraged and that using it is widely considered a weakness of the test environment. ## Example This is what will happen when navigating to a domain that has a self-signed TLS certificate using the Python client: ```python from selenium import webdriver from selenium.common import exceptions session = webdriver.Firefox() try: session.get("https://self-signed.badssl.com/") except exceptions.InsecureCertificateException as e: print("Hit insecure cert on {}".format(session.current_url)) ``` Output: ```plain Hit an insecure cert on https://self-signed.badssl.com/ ``` ## See also - [Navigate To](/en-US/docs/Web/WebDriver/Commands/NavigateTo) command - [Capabilities](/en-US/docs/Web/WebDriver/Capabilities) - [badssl.com](https://badssl.com/)
0
data/mdn-content/files/en-us/web/webdriver
data/mdn-content/files/en-us/web/webdriver/commands/index.md
--- title: Commands slug: Web/WebDriver/Commands page-type: landing-page browser-compat: webdriver.commands --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver")}} The following is a list of the available WebDriver commands. {{SubpagesWithSummaries}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/webdriver/commands
data/mdn-content/files/en-us/web/webdriver/commands/setwindowrect/index.md
--- title: Set Window Rect slug: Web/WebDriver/Commands/SetWindowRect page-type: webdriver-command browser-compat: webdriver.commands.SetWindowRect --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/commands")}} The _Set Window Rect_ [command](/en-US/docs/Web/WebDriver/Commands) of the [WebDriver](/en-US/docs/Web/WebDriver) API alters the size and position of the operating system window associated with the current [`window`](/en-US/docs/Web/API/Window). The command acts as the setter of [Get Window Rect](/en-US/docs/Web/WebDriver/Commands/GetWindowRect), which return object you can pass directly as this command's payload. Certain subsets of devices do not support setting the window dimensions or its position. On these configurations the command will return an [unsupported operating](/en-US/docs/Web/WebDriver/Errors/UnsupportedOperation) error. To avoid running into situations where calling this might error it is possible to call it conditionally on whether the [`setWindowRect` capability](/en-US/docs/Web/WebDriver/Capabilities/setWindowRect) is set to true for the session. Setting the window rect takes `x`, `y`, `width`, and `height` as input. All the fields are optional, e.g. the command may be called with an empty object, and in this case it will act as a no-op. To set the position both of `x` and `y` are required, and correspondingly both `width` and `height` are required for altering the window's dimensions. When setting the width or height, it is not guaranteed that the resulting window size will exactly match that which was requested. The driver is expected to clamp values that are larger than the physical screen dimensions, or smaller than the minimum window size. Some drivers may also have other limitations such as not being able to resize in single-pixel increments. For this reason, the returned `width` and `height` might not exactly match [`Window.outerWidth`](/en-US/docs/Web/API/Window/outerWidth) and [`Window.outerHeight`](/en-US/docs/Web/API/Window/outerHeight). Setting the window's position is similar in nature to calling [`Window.moveTo(x, y)`](/en-US/docs/Web/API/Window/moveTo), but differences itself by bypassing security restrictions related to window manipulation. The Set Window Rect command is blocking. ## Syntax | Method | URI template | | ----------------------------------------- | ----------------------------------- | | [POST](/en-US/docs/Web/HTTP/Methods/POST) | `/session/{session id}/window/rect` | ### URL parameters - `session id` - : Identifier of the session. ### Payload The input is a [`WindowRect`](/en-US/docs/Web/WebDriver/WindowRect) object: - `x` - : Horizontal position of the [`window`](/en-US/docs/Web/API/Window), which equivalent to [`Window.screenX`](/en-US/docs/Web/API/Window/screenX). Must be a number in the −(2^31) to 2^31 − 1 range, null, or undefined. - `y` - : Vertical position of the [`window`](/en-US/docs/Web/API/Window), which is equivalent to [`Window.screenY`](/en-US/docs/Web/API/Window/screenY). Must be a number in the −(2^31) to 2^31 − 1 range, null, or undefined. - `width` - : Outer width of the [`window`](/en-US/docs/Web/API/Window), which is equivalent to [`Window.outerWidth`](/en-US/docs/Web/API/Window/outerWidth). Must be a number in the 0 to 2^31 − 1 range, null, or undefined. - `height` - : Outer width of the [`window`](/en-US/docs/Web/API/Window), which is equivalent to [`Window.outerHeight`](/en-US/docs/Web/API/Window/outerHeight). Must be a number in the 0 to 2^31 − 1 range, null, or undefined. ### Response The response payload is a [`WindowRect`](/en-US/docs/Web/WebDriver/WebWindow): - `x` - : Horizontal position of the operating system window associated with [`window`](/en-US/docs/Web/API/Window), equivalent to [`Window.screenX`](/en-US/docs/Web/API/Window/screenX). - `y` - : Vertical position of the operating system window associated with [`window`](/en-US/docs/Web/API/Window), equivalent to [`Window.screenY`](/en-US/docs/Web/API/Window/screenY). - `width` - : Width of outer bounds of the operating system window associated with [`window`](/en-US/docs/Web/API/Window), equivalent to [`Window.outerWidth`](/en-US/docs/Web/API/Window/outerWidth). - `height` - : Height of the outer bounds of the operating system window associated with [`window`](/en-US/docs/Web/API/Window), equivalent to [`Window.outerHeight`](/en-US/docs/Web/API/Window/outerHeight). ### Errors - Invalid argument - : If any of the fields in the [`WindowRect`](/en-US/docs/Web/WebDriver/WindowRect) payload object do not meet the type or bounds constraints, or if only one of the `x`/`y` pair or `width`/`height` pair fields are specified. - [Invalid session ID](/en-US/docs/Web/WebDriver/Errors/InvalidSessionID) - : Session does not exist. - [No such window](/en-US/docs/Web/WebDriver/Errors/NoSuchWindow) - : If the [`window`](/en-US/docs/Web/API/Window) has been closed. - [Unexpected alert open](/en-US/docs/Web/WebDriver/Errors/UnexpectedAlertOpen) - : A user prompt, such as [`window.alert`](/en-US/docs/Web/API/Window/alert), blocks execution of command until it is dealt with. - [Unsupported operation](/en-US/docs/Web/WebDriver/Errors/UnsupportedOperation) - : If the driver does not support altering the window's size or position. This is usually the case on mobile devices, where the browser has a set dimension and cannot be moved around on the screen. You can inspect the [`setWindowRect` capability](/en-US/docs/Web/WebDriver/Capabilities/setWindowRect) to tell if the device supports this command. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`WebWindow`](/en-US/docs/Web/WebDriver/WebWindow) object - Associated commands: - [Get Window Rect](/en-US/docs/Web/WebDriver/Commands/GetWindowRect) - [Get Window Handle](/en-US/docs/Web/WebDriver/Commands/GetWindowHandle) - [Get Window Handles](/en-US/docs/Web/WebDriver/Commands/GetWindowHandles) - [Close Window](/en-US/docs/Web/WebDriver/Commands/CloseWindow)
0
data/mdn-content/files/en-us/web/webdriver/commands
data/mdn-content/files/en-us/web/webdriver/commands/getelementproperty/index.md
--- title: Get Element Property slug: Web/WebDriver/Commands/GetElementProperty page-type: webdriver-command browser-compat: webdriver.commands.GetElementProperty --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Commands")}} The _Get Element Property_ [command](/en-US/docs/Web/WebDriver/Commands) of the [WebDriver](/en-US/docs/Web/WebDriver) API returns the property of the referenced [web element](/en-US/docs/Web/WebDriver/WebElement). Given `<input value=foo>` where the user changes the value to `bar`, the returned property is `bar` rather than the initial value `foo`. This is equivalent to calling {{domxref("Element.getProperty")}} on the element. ## Syntax | Method | URI template | | ------ | ------------------------------------------------------------ | | `GET` | `/session/{session id}/element/{element id}/property/{name}` | ### URL parameters - `session id` - : Identifier of the session. - `element id` - : Identifier of the [web element](/en-US/docs/Web/WebDriver/WebElement) to get the tag name of. - `name` - : Identifier of the property of [web element](/en-US/docs/Web/WebDriver/WebElement) to get. ### Errors - [Session not created](/en-US/docs/Web/WebDriver/Errors/SessionNotCreated) - : Session does not exist. - [No such window](/en-US/docs/Web/WebDriver/Errors/NoSuchWindow) - : The [`window`](/en-US/docs/Web/API/Window) object has been discarded, indicating that the tab or window has been closed. - [Unexpected alert open](/en-US/docs/Web/WebDriver/Errors/UnexpectedAlertOpen) - : A user prompt, such as [`window.alert`](/en-US/docs/Web/API/Window/alert), blocks execution of command until it is dealt with. ## Examples Python: ```python import urllib from selenium import webdriver def inline(doc): return "data:text/html;charset=utf-8,{}".format(urllib.quote(doc)) session = webdriver.Firefox() session.get(inline("<input value=foo>")) textbox = driver.find_element_by_tag_name("input") textbox.send_keys("bar") print(text_box.get_attribute("value")) print(text_box.get_property("value")) ``` Output: ```plain foo bar ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Get Element Attribute](/en-US/docs/Web/WebDriver/Commands/GetElementAttribute) command - _[What is the difference between properties and attributes?](https://stackoverflow.com/questions/6003819/what-is-the-difference-between-properties-and-attributes-in-html)_ on Stack Overflow
0
data/mdn-content/files/en-us/web/webdriver/commands
data/mdn-content/files/en-us/web/webdriver/commands/getwindowhandles/index.md
--- title: Get Window Handles slug: Web/WebDriver/Commands/GetWindowHandles page-type: webdriver-command browser-compat: webdriver.commands.GetWindowHandles --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Commands")}} The _Get Window Handles_ [command](/en-US/docs/Web/WebDriver/Command) of the [WebDriver](/en-US/docs/Web/WebDriver) API returns a list of all [`WebWindow`](/en-US/docs/Web/WebDriver/WebWindow)s. Each tab or window, depending on whether you are using a tabbed browser, is associated by a _window handle_ that is used as a reference when [switching to the window](/en-US/docs/Web/WebDriver/Commands/SwitchToWindow). In order to determine whether or not a particular interaction with the browser opens a new window, one can obtain the set of window handles before the interaction is performed and compare it with the set after the action is performed. ## Syntax | Method | URI template | | ----------------------------------------- | -------------------------------------- | | [`GET`](/en-US/docs/Web/HTTP/Methods/GET) | `/session/{session id}/window/handles` | ### URL parameters - `session id` - : Identifier of the session. ### Errors - Invalid session ID - : Session does not exist. ## Example C#: ```cpp using System.Collections.ObjectModel; using OpenQA.Selenium.Firefox; namespace MDNWebDriverExamples { class Example { public static void Main(string[] args) { FirefoxDriver session = new FirefoxDriver(); session.ExecuteScript("window.open()"); ReadOnlyCollection<string> currentWindowHandles = session.WindowHandles; } } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Switch To Window](/en-US/docs/Web/WebDriver/Commands/SwitchToWindow) command - [Get Window Handle](/en-US/docs/Web/WebDriver/Commands/GetWindowHandle) command - [Close Window](/en-US/docs/Web/WebDriver/Commands/CloseWindow) command
0
data/mdn-content/files/en-us/web/webdriver/commands
data/mdn-content/files/en-us/web/webdriver/commands/gettimeouts/index.md
--- title: Get Timeouts slug: Web/WebDriver/Commands/GetTimeouts page-type: webdriver-command browser-compat: webdriver.commands.GetTimeouts --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Commands")}} The _Get Timeouts_ [command](/en-US/docs/Web/WebDriver/Commands) of the [WebDriver](/en-US/docs/Web/WebDriver) API returns the timeouts associated with the current session. The [session timeout](/en-US/docs/Web/WebDriver/Timeouts) durations control such behavior as timeouts on [script injection](/en-US/docs/Web/WebDriver/Timeouts#script), [document navigation](/en-US/docs/Web/WebDriver/Timeouts#pageload), and [element retrieval](/en-US/docs/Web/WebDriver/Timeouts#implicit). ## Syntax | Method | URI template | | ----------------------------------------- | -------------------------------- | | [`GET`](/en-US/docs/Web/HTTP/Methods/GET) | `/session/{session id}/timeouts` | ### URL parameters - `session id` - : Identifier of the session. ### Response The response payload is a [`Timeouts`](/en-US/docs/Web/WebDriver/Timeouts) object: - `implicit` - : Time in milliseconds to retry the [element location strategy](/en-US/docs/Web/WebDriver/WebElement) when finding an element. This defaults to 0, meaning the strategy is run only once. - `pageLoad` - : Time in milliseconds to wait for the document to finish loading. By default WebDriver will wait five minutes (or 300,000 ms). - `script` - : Scripts injected with [Execute Script](/en-US/docs/Web/WebDriver/Commands/ExecuteScript) or [Execute Async Script](/en-US/docs/Web/WebDriver/Commands/ExecuteAsyncScript) will run until they hit the script timeout duration, which is also given in milliseconds. The scripts will then be interrupted and a [script timeout error](/en-US/docs/Web/WebDriver/Errors/ScriptTimeoutError) will be returned. Defaults to 30 seconds (or 30,000 ms). ### Errors - [Invalid session ID](/en-US/docs/Web/WebDriver/Errors/InvalidSessionID) - : Session does not exist. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`Timeouts`](/en-US/docs/Web/WebDriver/Timeouts) object - [Set Timeouts](/en-US/docs/Web/WebDriver/Commands/SetTimeouts) command - [List of WebDriver commands](/en-US/docs/Web/WebDriver/Commands)
0
data/mdn-content/files/en-us/web/webdriver/commands
data/mdn-content/files/en-us/web/webdriver/commands/getelementattribute/index.md
--- title: Get Element Attribute slug: Web/WebDriver/Commands/GetElementAttribute page-type: webdriver-command browser-compat: webdriver.commands.GetElementAttribute --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Commands")}} The _Get Element Attribute_ [command](/en-US/docs/Web/WebDriver/Command) of the [WebDriver](/en-US/docs/Web/WebDriver) API returns the attribute of the referenced [web element](/en-US/docs/Web/WebDriver/WebElement). If for example the element is an {{HTMLElement("img")}}, the returned attribute is `"//TODO"`, which is equivalent to calling {{domxref("Element.getAttribute")}} on the element. For XML/XHTML documents it may be cased differently. ## Syntax | Method | URI template | | ------ | ------------------------------------------------------------- | | `GET` | `/session/{session id}/element/{element id}/attribute/{name}` | ### URL parameters - `session id` - : Identifier of the session. - `element id` - : Identifier of the [web element](/en-US/docs/Web/WebDriver/WebElement) to get the tag name of. - `name` - : Identifier of the attribute of [web element](/en-US/docs/Web/WebDriver/WebElement) to get. ### Errors - [Session not created](/en-US/docs/Web/WebDriver/Errors/SessionNotCreated) - : Session does not exist. - [No such window](/en-US/docs/Web/WebDriver/Errors/NoSuchWindow) - : The [`window`](/en-US/docs/Web/API/Window) object has been discarded, indicating that the tab or window has been closed. - [Unexpected alert open](/en-US/docs/Web/WebDriver/Errors/UnexpectedAlertOpen) - : A user prompt, such as [`window.alert`](/en-US/docs/Web/API/Window/alert), blocks execution of command until it is dealt with. ## Examples Python: ```python from selenium import webdriver session = webdriver.Firefox() session.get("https://google.com/?hl=en") search_box = session.find_element_by_id("q") print(search_box.get_attribute("id")) ``` Output: ```plain q ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/webdriver/commands
data/mdn-content/files/en-us/web/webdriver/commands/getelementtagname/index.md
--- title: Get Element Tag Name slug: Web/WebDriver/Commands/GetElementTagName page-type: webdriver-command browser-compat: webdriver.commands.GetElementTagName --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Commands")}} The _Get Element Tag Name_ [command](/en-US/docs/Web/WebDriver/Command) of the [WebDriver](/en-US/docs/Web/WebDriver) API returns the tag name of the referenced [web element](/en-US/docs/Web/WebDriver/WebElement). If for example the element is an {{HTMLElement("img")}}, the returned tag name is `"IMG"`, which is equivalent to calling {{domxref("Element.tagName")}} on the element. For XML/XHTML documents it may be cased differently. ## Syntax | Method | URI template | | ------ | ------------------------------------------------- | | `GET` | `/session/{session id}/element/{element id}/name` | ### URL parameters - `session id` - : Identifier of the session. - `element id` - : Identifier of the [web element](/en-US/docs/Web/WebDriver/WebElement) to get the tag name of. ### Errors - [Session not created](/en-US/docs/Web/WebDriver/Errors/SessionNotCreated) - : Session does not exist. - [No such window](/en-US/docs/Web/WebDriver/Errors/NoSuchWindow) - : The [`window`](/en-US/docs/Web/API/Window) object has been discarded, indicating that the tab or window has been closed. - [Unexpected alert open](/en-US/docs/Web/WebDriver/Errors/UnexpectedAlertOpen) - : A user prompt, such as [`window.alert`](/en-US/docs/Web/API/Window/alert), blocks execution of command until it is dealt with. ## Examples Python: ```python from selenium import webdriver session = webdriver.Firefox() session.get("https://google.com/?hl=en") search_box = driver.find_element_by_id("q") print(search_box.tag_name) ``` Output: ```plain INPUT ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/webdriver/commands
data/mdn-content/files/en-us/web/webdriver/commands/closewindow/index.md
--- title: Close Window slug: Web/WebDriver/Commands/CloseWindow page-type: webdriver-command browser-compat: webdriver.commands.CloseWindow --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Commands")}} The _Close Window_ [command](/en-US/docs/Web/WebDriver/Command) of the [WebDriver](/en-US/docs/Web/WebDriver) API closes the current top-level browsing context (window or tab) and returns with the list of currently open [`WebWindow`](/en-US/docs/Web/WebDriver/WebWindow)s. If it is the last window that is being closed, the WebDriver session will implicitly be deleted. Subsequent commands after the session is ended will therefore cause [invalid session ID](/en-US/docs/Web/WebDriver/Errors/InvalidSessionID) errors. ## Syntax | Method | URI template | | ----------------------------------------------- | ------------------------------ | | [`DELETE`](/en-US/docs/Web/HTTP/Methods/DELETE) | `/session/{session id}/window` | ### URL parameters - `session id` - : Identifier of the session. ### Errors - [Invalid session ID](/en-US/docs/Web/WebDriver/Errors/InvalidSessionID) - : Session does not exist. - [Unexpected alert open](/en-US/docs/Web/WebDriver/Errors/UnexpectedAlertOpen) - : A user prompt, such as [`window.alert`](/en-US/docs/Web/API/Window/alert), blocks execution of command until it is dealt with. ## Example Python: ```python from selenium import webdriver session = webdriver.Firefox() original_window = session.window_handle new_window = session.execute_script("return window.open()") session.switch_to.window(new_window) session.close() session.switch_to.window(original_window) ``` C#: ```cpp using OpenQA.Selenium.Firefox; namespace MDNWebDriverExamples { class Example { public static void Main(string[] args) { FirefoxDriver session = new FirefoxDriver(); string original_window = session.CurrentWindowHandle;// Optional if you want to store the handle in a variable session.ExecuteScript("window.open()"); session.SwitchTo().Window(session.WindowHandles[1]); // Switch to the second window session.Close(); // Close current window session.SwitchTo().Window(session.WindowHandles[0]); // Switch back to the first window } } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Switch To Window](/en-US/docs/Web/WebDriver/Commands/SwitchToWindow) command - [Get Window Handle](/en-US/docs/Web/WebDriver/Commands/GetWindowHandle) command - [Get Window Handles](/en-US/docs/Web/WebDriver/Commands/GetWindowHandles) command
0
data/mdn-content/files/en-us/web/webdriver/commands
data/mdn-content/files/en-us/web/webdriver/commands/new_window/index.md
--- title: New Window slug: Web/WebDriver/Commands/New_Window page-type: webdriver-command browser-compat: webdriver.commands.NewWindow --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Commands")}} The _New Window_ [command](/en-US/docs/Web/WebDriver/Commands) of the [WebDriver](/en-US/docs/Web/WebDriver) API opens a new top-level browsing context of type _window_ or _tab_, and returns with a dictionary containing the _handle_ of the new [WebWindow](/en-US/docs/Web/WebDriver/WebWindow) and its created _type_. If the requested _type_ cannot be created by the browser, the alternative type will be tried to create. ## Syntax | Method | URI template | | --------------------------------------------- | ---------------------------------- | | [`POST`](/en-US/docs/Web/HTTP/Methods/DELETE) | `/session/{session id}/window/new` | ### URL parameters - `session id` - : Identifier of the session. ### Payload The input is an object: - `type` - : Requested type of top-level browsing context. ### Response The response payload is an object: - handle - : The handle of the new [WebWindow](/en-US/docs/Web/WebDriver/WebWindow). - type - : The created type of top-level browsing context. ### Errors - [Invalid session ID](/en-US/docs/Web/WebDriver/Errors/InvalidSessionID) - : Session does not exist. - [No such window](/en-US/docs/Web/WebDriver/Errors/NoSuchWindow) - : If the [`window`](/en-US/docs/Web/API/Window) has been closed. - [Unexpected alert open](/en-US/docs/Web/WebDriver/Errors/UnexpectedAlertOpen) - : A user prompt, such as [`window.alert`](/en-US/docs/Web/API/Window/alert), blocks execution of command until it is dealt with. - [Unsupported Operation](/en-US/docs/Web/WebDriver/Errors/UnsupportedOperation) - : The driver or browser doesn't support the command for some reason (e.g., when it is not possible to create a new tab or window). ## Example ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Close Window](/en-US/docs/Web/WebDriver/Commands/CloseWindow) command
0
data/mdn-content/files/en-us/web/webdriver/commands
data/mdn-content/files/en-us/web/webdriver/commands/settimeouts/index.md
--- title: Set Timeouts slug: Web/WebDriver/Commands/SetTimeouts page-type: webdriver-command browser-compat: webdriver.commands.SetTimeouts --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Commands")}} The _Set Timeouts_ [command](/en-US/docs/Web/WebDriver/Commands) of the [WebDriver](/en-US/docs/Web/WebDriver) API sets the timeouts associated with the current session. The [session timeout](/en-US/docs/Web/WebDriver/Timeouts) durations control such behavior as timeouts on [script injection](/en-US/docs/Web/WebDriver/Timeouts#script), [document navigation](/en-US/docs/Web/WebDriver/Timeouts#pageload), and [element retrieval](/en-US/docs/Web/WebDriver/Timeouts#implicit). ## Syntax | Method | URI template | | ------------------------------------------ | -------------------------------- | | [`POST`](/en-US/docs/Web/HTTP/Methods/GET) | `/session/{session id}/timeouts` | ### URL parameters - `session id` - : Identifier of the session. ### Payload The input is a [`Timeouts`](/en-US/docs/Web/WebDriver/Timeouts) object: - `implicit` - : Time in milliseconds to retry the [element location strategy](/en-US/docs/Web/WebDriver/WebElement) when finding an element. This defaults to 0, meaning the strategy is run only once. - `pageLoad` - : Time in milliseconds to wait for the document to finish loading. By default, WebDriver will wait five minutes (or 300,000 ms). - `script` - : Scripts injected with [Execute Script](/en-US/docs/Web/WebDriver/Commands/ExecuteScript) or [Execute Async Script](/en-US/docs/Web/WebDriver/Commands/ExecuteAsyncScript) will run until they hit the script timeout duration, which is also given in milliseconds. The scripts will then be interrupted and a [script timeout error](/en-US/docs/Web/WebDriver/Errors/ScriptTimeoutError) will be returned. Defaults to 30 seconds (or 30,000 ms). ### Errors - [Invalid session ID](/en-US/docs/Web/WebDriver/Errors/InvalidSessionID) - : Session does not exist. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`Timeouts`](/en-US/docs/Web/WebDriver/Timeouts) object - [List of WebDriver commands](/en-US/docs/Web/WebDriver/Commands)
0
data/mdn-content/files/en-us/web/webdriver/commands
data/mdn-content/files/en-us/web/webdriver/commands/getwindowrect/index.md
--- title: Get Window Rect slug: Web/WebDriver/Commands/GetWindowRect page-type: webdriver-command browser-compat: webdriver.commands.GetWindowRect --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Commands")}} The _Get Window Rect_ [command](/en-US/docs/Web/WebDriver/Commands) of the [WebDriver](/en-US/docs/Web/WebDriver) API returns the size and position of the given [`WebElement`](/en-US/docs/Web/WebDriver/WebElement). Many [WebDriver clients](/en-US/docs/Web/WebDriver/Clients) present separate API methods for getting an element's location and dimensions, but as an optimization they both use this primitive. The command operates on the currently selected window, and returns size and position of the operating system window. The returned [`WindowRect`](/en-US/docs/Web/WebDriver/WindowRect) can be used as input for the [Set Window Rect](/en-US/docs/Web/WebDriver/SetWindowRect) command, which is for manipulating a window's position and dimensions. ## Syntax | Method | URI template | | ----------------------------------------- | ----------------------------------- | | [`GET`](/en-US/docs/Web/HTTP/Methods/GET) | `/session/{session id}/window/rect` | ### URL parameters - `session id` - : Identifier of the session. ### Response The response payload is a [`WindowRect`](/en-US/docs/Web/WebDriver/WebWindow): - `x` - : Horizontal position of the operating system window associated with [`window`](/en-US/docs/Web/API/Window), equivalent to [`Window.screenX`](/en-US/docs/Web/API/Window/screenX). - `y` - : Vertical position of the operating system window associated with [`window`](/en-US/docs/Web/API/Window), equivalent to [`Window.screenY`](/en-US/docs/Web/API/Window/screenY). - `width` - : Width of outer bounds of the operating system window associated with [`window`](/en-US/docs/Web/API/Window), equivalent to [`Window.outerWidth`](/en-US/docs/Web/API/Window/outerWidth). - `height` - : Height of the outer bounds of the operating system window associated with [`window`](/en-US/docs/Web/API/Window), equivalent to [`Window.outerHeight`](/en-US/docs/Web/API/Window/outerHeight). ### Errors - [Invalid session ID](/en-US/docs/Web/WebDriver/Errors/InvalidSessionID) - : Session does not exist. - [Unexpected alert open](/en-US/docs/Web/WebDriver/Errors/UnexpectedAlertOpen) - : A user prompt, such as [`window.alert`](/en-US/docs/Web/API/Window/alert), blocks execution of command until it is dealt with. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - WebWindow - Associated commands: - [Set Window Rect](/en-US/docs/Web/WebDriver/Commands/SetWindowRect) - [Get Window Handle](/en-US/docs/Web/WebDriver/Commands/GetWindowHandle) - [Get Window Handles](/en-US/docs/Web/WebDriver/Commands/GetWindowHandles) - [Close Window](/en-US/docs/Web/WebDriver/Commands/CloseWindow)
0
data/mdn-content/files/en-us/web/webdriver
data/mdn-content/files/en-us/web/webdriver/timeouts/index.md
--- title: Timeouts slug: Web/WebDriver/Timeouts page-type: guide --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver")}} Associated with a [WebDriver](/en-US/docs/Web/WebDriver) session are various timeout definitions that control behavior for [script injection](#script), [document navigation](#pageload), and [element retrieval](#implicit). You will find the _[timeouts object](#payload)_ used in a few different contexts. It can be used as configuration when [creating a new session](/en-US/docs/Web/WebDriver/Commands/NewSession) through [capabilities](/en-US/docs/Web/WebDriver/Capabilities), it is returned as part of the matched, effective capabilities after the session has been created, and it is used as input and output for the [Set Timeouts](/en-US/docs/Web/WebDriver/Commands/SetTimeouts) and [Get Timeouts](/en-US/docs/Web/WebDriver/Commands/GetTimeouts) commands. The default values can be overridden when [creating the session](/en-US/docs/Web/WebDriver/Commands/NewSession) and they will be effective until the session is closed. If you call [Set Timeouts](/en-US/docs/Web/WebDriver/Commands/SetTimeouts) during the session's lifetime, the defaults are overridden and will take effect for the lifetime of the session or until [Set Timeouts](/en-US/docs/Web/WebDriver/Commands/SetTimeouts) is called again. ## Payload The **timeouts object** is a JSON Object that either describes the current session's timeout values, or which is used as input when configuring the timeouts: - `implicit` - : Time in milliseconds to retry the [element location strategy](/en-US/docs/Web/WebDriver/WebElement) when finding an element. This defaults to 0, meaning the strategy is run only once. - `pageLoad` - : Time in milliseconds to wait for the document to finish loading. By default WebDriver will wait five minutes (or 300,000 ms). - `script` - : Scripts injected with [Execute Script](/en-US/docs/Web/WebDriver/Commands/ExecuteScript) or [Execute Async Script](/en-US/docs/Web/WebDriver/Commands/ExecuteAsyncScript) will run until they hit the script timeout duration, which is also given in milliseconds. The scripts will then be interrupted and a [script timeout error](/en-US/docs/Web/WebDriver/Errors/ScriptTimeoutError) will be returned. Defaults to 30 seconds (or 30,000 ms). When the object is used as input for the [Set Timeouts](/en-US/docs/Web/WebDriver/Commands/SetTimeouts) command or as part of the [timeouts capability](/en-US/docs/Web/WebDriver/Capabilities) when [creating a new session](/en-US/docs/Web/WebDriver/Commands/NewSession), all fields are optional. This means you can configure zero or more of the timeout duration values individually or all at once. When it is returned by the driver, either by [Get Timeouts](/en-US/docs/Web/WebDriver/Commands/GetTimeouts) or in the matched capabilities from [having created a session](/en-US/docs/Web/WebDriver/Commands/NewSession), all fields will be present. ## Examples ### Setting timeouts at session creation You can override the default session timeouts by providing a [timeouts capabilities object](/en-US/docs/Web/WebDriver/Capabilities) when you start a new WebDriver session: ```python import urllib from selenium import webdriver def inline(doc): return "data:text/html;charset=utf-8,{}".format(urllib.quote(doc)) session = webdriver.Firefox(capabilities={"timeouts": {"implicit": 4500}}) session.get(inline(""" <h1>Example</h1> <script> // Inserts <p> below <h1> after 2.5 seconds: setTimeout(() => { const delayedElement = document.createElement("p"); const h1 = document.querySelector("h1"); document.body.insertAfter(delayedElement, h1); }, 2500); </script> """) # This will cause the driver to wait 4.5 seconds # for #foo to appear in the DOM: delayed_element = session.find_element_by_tag_name("p") ``` ### Setting and getting timeouts at runtime Timeouts can also be set at runtime using the Set Timeouts command. These will override the session's current timeouts and will take effect for the entire lifetime of the session or until a subsequent call is made to the same command: ```python from selenium import webdriver session = webdriver.Firefox() session.set_timeouts({"implicit": 4.5}) print(session.get_timeouts) ``` The output will be in seconds because this is the idiomatic time unit in Python: ```json { "implicit": 4.5, "script": 300, "pageLoad": 30000 } ``` {{QuickLinksWithSubpages}}
0
data/mdn-content/files/en-us/web/webdriver
data/mdn-content/files/en-us/web/webdriver/capabilities/index.md
--- title: Capabilities slug: Web/WebDriver/Capabilities page-type: landing-page --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver")}} WebDriver **_capabilities_** are used to communicate the features supported by a [session](/en-US/docs/Web/WebDriver). A client may also use capabilities to define which features it requires the driver to satisfy when [creating a new session](/en-US/docs/Web/WebDriver/Commands/NewSession). When a WebDriver session is created it returns a set of capabilities describing the negotiated, effective capabilities of the session. Some of the capabilities included in this set are [standard and shared between all browsers](#list_of_capabilities), but the set may also contain [browser-specific capabilities](#vendor-specific_capabilities) and these are always prefixed. ## Capabilities negotiation Capabilities can be used to require a driver that supports a certain subset of features. This can be used to require certain browser features, such as the [ability to resize the window dimensions](/en-US/docs/Web/WebDriver/Capabilities/setWindowRect), but is also used in distributed environments to select a particular browser configuration from a matrix of choices. Selecting a particular web browser or platform only makes sense when you use a remote WebDriver. In this case the client makes contact with WebDriver through one or more intermediary nodes which negotiates which driver to return to you based on the capabilities it receives. The capabilities object is a selection mechanism that limits which driver configurations the server will return. If you request a Firefox instance using `browserName` and Firefox is not installed on the remote, or macOS from a remote that only supports Linux, you may be out of luck. But occasionally you may not care which specific operating system or web browser your session has: you just want a session that has some _capability_. The selection process, or the _capabilities negotiation_, is done through `alwaysMatch` and `firstMatch`. ### `alwaysMatch` As the name suggests, capabilities described inside the `alwaysMatch` capabilities object are features you _require_ the session to have. If the server can not provide what features you require, it will fail. If for example you ask for Firefox version 62 on a system that only has 60 installed, the session creation will fail: ```json { "capabilities": { "alwaysMatch": { "browserName": "firefox", "browserVersion": "60" } } } ``` ### `firstMatch` The `firstMatch` field accepts _an array_ of capabilities objects which will be matched in turn until one matches what the server can provide, or it will fail. This can be useful when you want a driver that runs on macOS or Linux, but not Windows: ```json { "capabilities": { "firstMatch": [{ "platformName": "macos" }, { "platformName": "linux" }] } } ``` ### Combining `alwaysMatch` and `firstMatch` `firstMatch` can of course be combined with `alwaysMatch` to narrow down the selection. If for example you a driver that runs on macOS or Linux but it _has_ to be Firefox: ```json { "capabilities": { "alwaysMatch": { "browserName": "firefox" }, "firstMatch": [{ "platformName": "macos" }, { "platformName": "linux" }] } } ``` The previous example is exactly equivalent to putting the Firefox requirement in each `firstMatch` arm: ```json { "capabilities": { "firstMatch": [ { "browserName": "firefox", "platformName": "macos" }, { "browserName": "firefox", "platformName": "linux" } ] } } ``` Which you choose of the two preceding examples is not important, but it can matter when pass along browser configuration. To avoid unnecessarily repeating data, such as profiles, it is advisable to make use of `alwaysMatch` so that this data is only transmitted across the wire once: ```json { "capabilities": { "alwaysMatch": { "browserName": "firefox", "moz:firefoxOptions": { "profile": "<base64 encoded profile>", "args": ["-headless"], "prefs": { "dom.ipc.processCount": 8 }, "log": { "level": "trace" } } }, "firstMatch": [{ "platformName": "macos" }, { "platformName": "linux" }] } } ``` ## List of capabilities - [`browserName`](/en-US/docs/Web/WebDriver/Capabilities/browserName) - [`browserVersion`](/en-US/docs/Web/WebDriver/Capabilities/browserVersion) - [`platformName`](/en-US/docs/Web/WebDriver/Capabilities/platformName) - [`acceptInsecureCerts`](/en-US/docs/Web/WebDriver/Capabilities/acceptInsecureCerts): This capability communicates whether expired or invalid [TLS certificates](/en-US/docs/Glossary/TLS) are checked when [navigating](/en-US/docs/Web/WebDriver/Commands/NavigateTo). If the capability is false, an [insecure certificate](/en-US/docs/Web/WebDriver/Errors/InsecureCertificate) error will be returned as navigation encounters domains with certificate problems. Otherwise, self-signed or otherwise invalid certificates will be implicitly trusted by the browser on navigation. The capability has effect for the lifetime of the session. - [`pageLoadStrategy`](/en-US/docs/Web/WebDriver/Capabilities/pageLoadStrategy) - [`proxy`](/en-US/docs/Web/WebDriver/Capabilities/proxy) - [`setWindowRect`](/en-US/docs/Web/WebDriver/Capabilities/setWindowRect) - [`timeouts`](/en-US/docs/Web/WebDriver/Capabilities/timeouts) - [`unhandledPromptBehavior`](/en-US/docs/Web/WebDriver/Capabilities/unhandledPromptBehavior) ## Vendor-specific capabilities In addition to the [standard capabilities](#list_of_capabilities) WebDriver allows third-parties to _extend_ the set of capabilities to match their needs. Browser vendors and suppliers of drivers typically use extension capabilities to provide configuration to the browser, but they can also be used by intermediaries for arbitrary blobs of information. - [Firefox capabilities](/en-US/docs/Web/WebDriver/Capabilities/firefoxOptions) (`moz:firefoxOptions`) - [Chrome capabilities](/en-US/docs/Web/WebDriver/Capabilities/goog/chromeOptions) (`goog:chromeOptions`) ## Legacy capabilities The majority of Selenium clients use `desiredCapabilities` and `requiredCapabilities` to configure the new session. These are very similar to `firstMatch` and `alwaysMatch` described above. Some drivers support these legacy capabilities, but they are deprecated and should be avoided. Converting a legacy capabilities object into the new style is easy. The first thing you need to know is that `alwaysMatch`/`firstMatch` is _always_ wrapped inside a `capabilities` JSON Object, whereas `desiredCapabilities`/`requiredCapabilities` exists at the top level. Generally speaking, anything that has previously gone in `desiredCapabilities` should go in a `firstMatch` branch arm to achieve the same effect. Take this deprecated capabilities object: ```json { "desiredCapabilities": { "browserName": "firefox" } } ``` This would be functionally equivalent in the new style: ```json { "capabilities": { "firstMatch": [{ "browserName": "firefox" }] } } ``` But because there is only one `firstMatch` arm, and we know that session creation will fail if the server doesn't have a Firefox installed, it is also equivalent to this: ```json { "capabilities": { "alwaysMatch": { "browserName": "firefox" } } } ``` ## See also - [New Session](/en-US/docs/Web/WebDriver/Commands/NewSession) command - [Delete Session](/en-US/docs/Web/WebDriver/Commands/NewSession) command
0
data/mdn-content/files/en-us/web/webdriver/capabilities
data/mdn-content/files/en-us/web/webdriver/capabilities/firefoxoptions/index.md
--- title: firefoxOptions slug: Web/WebDriver/Capabilities/firefoxOptions page-type: webdriver-capability --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Capabilities")}} The **`moz:firefoxOptions` capability** is a namespaced set of capabilities specific to [Firefox](https://www.mozilla.org/en-US/firefox/). It is used to control the behavior of Firefox and can be used as a member of [`alwaysMatch`](/en-US/docs/Web/WebDriver/Capabilities#alwaysmatch) or as a member of one of the [`firstMatch`](/en-US/docs/Web/WebDriver/Capabilities#firstmatch) entries. It is used to define options which control how Firefox gets started and run. `moz:firefoxOptions` is a JSON Object which may contain any of the following fields: ##### `binary` (string) Absolute path to the custom Firefox binary to use. On macOS you may either give the path to the application bundle, i.e. `/Applications/Firefox.app`, or the absolute path to the executable binary inside this bundle, for example `/Applications/Firefox.app/Contents/MacOS/firefox-bin`. geckodriver will attempt to deduce the default location of Firefox on the current system if left undefined. The default locations of Firefox are: <table class="standard-table"> <thead> <tr> <th scope="col">System</th> <th scope="col">Default location</th> </tr> </thead> <tbody> <tr> <td>macOS</td> <td> <ol> <li> <code>/Applications/Firefox.app/Contents/MacOS/firefox-bin</code> </li> <li> <code >$HOME/Applications/Firefox.app/Contents/MacOS/firefox-bin</code > </li> </ol> </td> </tr> <tr> <td>Linux<br />BSD</td> <td> <p> First <code>firefox</code> found on the system path. This is equivalent to the output of running <a href="https://manpages.debian.org/stretch/debianutils/which.1.en.html" >which(1)</a >: </p> <pre class="brush: plain"> % which firefox /usr/bin/firefox </pre > </td> </tr> <tr> <td>Windows</td> <td> <p>From the Window system registry:</p> <ol> <li> <code >HKEY_LOCAL_MACHINE\SOFTWARE WOW6432Node\Mozilla\Mozilla Firefox\[VERSION]\Main\PathToExe</code > </li> <li> <code >HKEY_LOCAL_MACHINE\SOFTWARE\Mozilla\Mozilla Firefox\[VERSION]\Main\PathToExe</code > </li> </ol> </td> </tr> </tbody> </table> ##### `args` (array of strings) Command line arguments to pass to the Firefox binary. These must include the leading dash (`-`) where required, e.g. `["-headless"]`. To have geckodriver pick up an existing [profile](#profile) on the local filesystem, you may pass `["-profile", "/path/to/profile"]`. But if a profile has to be transferred to a target machine it is recommended to use the `profile` entry. ##### `profile` (string) Base64-encoded ZIP of a profile directory to use for the Firefox instance. This may be used to e.g. install extensions or custom certificates, but for setting custom preferences we recommend using the `prefs` ([Preferences Object](#prefs)) entry instead. Profiles are created in the systems temporary folder. This is also where the encoded profile is extracted when `profile` is provided. By default geckodriver will create a new profile in this location. The effective profile in use by the WebDriver session is returned to the user in the `moz:profile` capability in the [new session response](/en-US/docs/Web/WebDriver/Commands/NewSession). To have geckodriver pick up an existing profile on the filesystem, please set the `args` field to `{"args": ["-profile", "/path/to/your/profile"]}`. Note that if you use a remote client targeting a server on a different system, the profile must already exist on the target system. ##### `log` (Log object) To increase the logging verbosity of geckodriver and Firefox, you may pass a [`log`](#log) object that may look like `{"log": {"level": "trace"}}` to include all trace-level logs and above ##### `prefs` (Preferences object) Map of preference name to preference value, which can be a string, a boolean or an integer. ### Android Starting with geckodriver 0.26.0 additional capabilities exist if Firefox or an application embedding [GeckoView](https://wiki.mozilla.org/Mobile/GeckoView) has to be controlled on Android: #### `androidPackage` (string, required) The package name of Firefox, e.g. `org.mozilla.firefox`, `org.mozilla.firefox_beta,` or `org.mozilla.fennec` depending on the release channel, or the package name of the application embedding GeckoView, e.g. `org.mozilla.geckoview_example`. #### `androidActivity` (string, optional) The fully qualified class name of the activity to be launched, e.g. `.GeckoViewActivity`. If not specified, the package's default activity will be used. #### `androidDeviceSerial` (string, optional) The serial number of the device on which to launch the application. If not specified and multiple devices are attached, an error will be returned. #### `androidIntentArguments` (array of strings, optional) Arguments to launch the intent with. Under the hood, geckodriver uses [Android am](https://developer.android.com/studio/command-line/adb#am) to start the Android application under test. The given intent arguments are appended to the `am start` command. See Android's [specification for intent arguments](https://developer.android.com/studio/command-line/adb#IntentSpec) for details. This allows to control how the application is launched and to include optional extras for enabling and disabling features. For example, to launch with the view action and a specified URL before navigating as part of a test, include: ```json { "androidIntentArguments": [ "-a", "android.intent.action.VIEW", "-d", "https://example.com" ] } ``` For example, to specify a boolean extra that can be processed with [android.content.Intent.getBooleanExtra](<https://developer.android.com/reference/android/content/Intent#getBooleanExtra(java.lang.String,%20boolean)>), include: ```json { "androidIntentArguments": ["--ez", "customBooleanFlagName", "true"] } ``` #### `env` (Env object) Map of environment variable name to environment variable value, both of which must be strings, that will be forwarded to application process running on the Android device. ### Log object A JSON Object that may have any of these fields: #### `level` (string) Set the level of verbosity of geckodriver and Firefox. Available levels are `trace`, `debug`, `config`, `info`, `warn`, `error`, and `fatal`. If left undefined the default is `info`. The value is treated case-insensitively. ### Preferences object A JSON Object with one entry per preference to set. The preference will be written to the [profile](#profile) before starting Firefox. A full list of available preferences is available from visiting "about:config" in your Firefox browser. Some of these are documented in [this source](https://searchfox.org/mozilla-central/source/modules/libpref/init/all.js) file. An example of a preference object: ```json { "dom.ipc.processCount": 8, "javascript.options.showInConsole": false } ``` ### Env object A JSON Object with one entry per environment variable to set. On Desktop, the Firefox under test will launch with given variable in its environment. On Android, the GeckoView-based App will have the given variable added to the `env` block in its configuration YAML. An example of an env object: ```json { "MOZ_LOG": "nsHttp:5", "MOZ_LOG_FILE": "/mnt/sdcard/log" } ``` ## Example The following is an example of a full [capabilities object](/en-US/docs/Web/WebDriver/Capabilities) that selects a specific Firefox binary to run with a prepared [profile](#profile) from the filesystem in [headless mode](https://hacks.mozilla.org/2017/12/using-headless-mode-in-firefox/). It also increases the number of IPC processes through a preference, turns off chrome errors/warnings in the console, and enables more verbose logging: ```json { "capabilities": { "alwaysMatch": { "moz:firefoxOptions": { "binary": "/usr/local/firefox/bin/firefox", "args": ["-headless", "-profile", "/path/to/my/profile"], "prefs": { "dom.ipc.processCount": 8, "javascript.options.showInConsole": false }, "log": { "level": "trace" }, "env": { "MOZ_LOG": "nsHttp:5", "MOZ_LOG_FILE": "/path/to/my/profile/log" } } } } } ``` The [`moz:firefoxOptions`](#firefoxoptions) must be placed—as above—inside [`alwaysMatch`](/en-US/docs/Web/WebDriver/Capabilities#alwaysmatch), or in one of the [`firstMatch`](/en-US/docs/Web/WebDriver/Capabilities#firstmatch) [capabilities objects](/en-US/docs/Web/WebDriver/Capabilities) as seen here: ```json { "capabilities": { "firstMatch": [ {"moz:firefoxOptions": …} ] } } ``` ### Android This runs the GeckoView example application as installed on the first Android emulator running on the host machine: ```json { "capabilities": { "alwaysMatch": { "moz:firefoxOptions": { "androidPackage": "org.mozilla.geckoview_example", "androidActivity": "org.mozilla.geckoview_example.GeckoView", "androidDeviceSerial": "emulator-5554", "androidIntentArguments": ["-d", "http://example.org"], "env": { "MOZ_LOG": "nsHttp:5", "MOZ_LOG_FILE": "/mnt/sdcard/log" } } } } } ``` ## See also - [geckodriver's documentation on supported Firefox capabilities](https://firefox-source-docs.mozilla.org/testing/geckodriver/Capabilities.html) - [Chrome-specific WebDriver capabilities](https://chromedriver.chromium.org/capabilities) (`goog:chromeOptions)` - [List of WebDriver capabilities](/en-US/docs/Web/WebDriver/Capabilities) - [New Session](/en-US/docs/Web/WebDriver/Commands/NewSession) command {{QuickLinksWithSubpages}}
0
data/mdn-content/files/en-us/web/webdriver/capabilities
data/mdn-content/files/en-us/web/webdriver/capabilities/websocketurl/index.md
--- title: webSocketUrl slug: Web/WebDriver/Capabilities/webSocketUrl page-type: webdriver-capability --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Capabilities")}} With the `webSocketUrl` capability set to `true` a WebSocket server will be started in the browser, supporting bidirectional communication by using the [WebDriver BiDi protocol](https://w3c.github.io/webdriver-bidi/). When the [New Session](/en-US/docs/Web/WebDriver/Commands/NewSession) request has the `webSocketUrl` capability set to `true`, and the session starts successfully, the value of the `capabilities` field in the response will have a `webSocketUrl` property set to the URL of the WebSocket server. ## Example Requesting the WebSocket URL by setting the `webSocketUrl` capability to `true`: Request: ```http POST /session HTTP/1.1 {"capabilities": {"alwaysMatch": {"webSocketUrl": true}}} ``` Response: ```json {"value":{"capabilities":{"webSocketUrl":"ws://localhost:9222/session/571f206f-c3fe-794c-9218-77fa89595eb9", [..]}, "sessionId":"571f206f-c3fe-794c-9218-77fa89595eb9"}} ``` ## See also - [List of WebDriver capabilities](/en-US/docs/Web/WebDriver/Capabilities) - [New Session](/en-US/docs/Web/WebDriver/Commands/NewSession) command - [Establishing a WebDriver BiDi connection](https://w3c.github.io/webdriver-bidi/#establishing)
0
data/mdn-content/files/en-us/web/webdriver/capabilities
data/mdn-content/files/en-us/web/webdriver/capabilities/acceptinsecurecerts/index.md
--- title: acceptInsecureCerts slug: Web/WebDriver/Capabilities/acceptInsecureCerts page-type: webdriver-capability --- {{QuickLinksWithSubpages("/en-US/docs/Web/WebDriver/Capabilities")}} The **`acceptInsecureCerts` capability** communicates whether expired or invalid [TLS certificates](/en-US/docs/Glossary/TLS) are checked when [navigating](/en-US/docs/Web/WebDriver/Commands/NavigateTo). When the capability is false, an [insecure certificate](/en-US/docs/Web/WebDriver/Errors/InsecureCertificate) error will be returned as navigation encounters domains with certificate problems. Otherwise, self-signed or otherwise invalid certificates will be implicitly trusted by the browser on navigation. The capability has effect for the lifetime of the session. ## Example Using the `acceptInsecureCerts` capability you can bypass, or implicitly trust, TLS certificates that the certificate service in the browser does not trust: ```python from selenium import webdriver from selenium.common import exceptions session = webdriver.Firefox(capabilities={"acceptInsecureCerts": True}) session.get("https://self-signed.badssl.com/") print(session.current_url) ``` Output: ```url https://self-signed.badssl.com/ ``` ## See also - [List of WebDriver capabilities](/en-US/docs/Web/WebDriver/Capabilities) - [Navigate To](/en-US/docs/Web/WebDriver/Commands/NavigateTo) command - [New Session](/en-US/docs/Web/WebDriver/Commands/NewSession) command
0
data/mdn-content/files/en-us/web
data/mdn-content/files/en-us/web/css/index.md
--- title: "CSS: Cascading Style Sheets" slug: Web/CSS page-type: landing-page --- {{CSSRef}} **Cascading Style Sheets** (**CSS**) is a [stylesheet](/en-US/docs/Web/API/StyleSheet) language used to describe the presentation of a document written in [HTML](/en-US/docs/Web/HTML) or [XML](/en-US/docs/Web/XML/XML_introduction) (including XML dialects such as [SVG](/en-US/docs/Web/SVG), [MathML](/en-US/docs/Web/MathML) or {{Glossary("XHTML")}}). CSS describes how elements should be rendered on screen, on paper, in speech, or on other media. CSS is among the core languages of the **open web** and is standardized across Web browsers according to [W3C specifications](https://www.w3.org/Style/CSS/#specs). Previously, the development of various parts of CSS specification was done synchronously, which allowed the versioning of the latest recommendations. You might have heard about CSS1, CSS2.1, or even CSS3. There will never be a CSS3 or a CSS4; rather, everything is now CSS without a version number. After CSS 2.1, the scope of the specification increased significantly and the progress on different CSS modules started to differ so much, that it became more effective to [develop and release recommendations separately per module](https://www.w3.org/Style/CSS/current-work). Instead of versioning the CSS specification, W3C now periodically takes a snapshot of [the latest stable state of the CSS specification](https://www.w3.org/TR/css/) and individual modules progress. CSS modules now have version numbers, or levels, such as [CSS Color Module Level 5](https://drafts.csswg.org/css-color-5/). ## Key resources - CSS Introduction - : If you're new to web development, be sure to read our [CSS basics](/en-US/docs/Learn/Getting_started_with_the_web/CSS_basics) article to learn what CSS is and how to use it. - CSS Tutorials - : Our [CSS learning area](/en-US/docs/Learn/CSS) contains a wealth of tutorials to take you from beginner level to proficiency, covering all the fundamentals. - CSS Reference - : Our [exhaustive CSS reference](/en-US/docs/Web/CSS/Reference) for seasoned Web developers describes every property and concept of CSS. > **Callout:** > > #### Looking to become a front-end web developer? > > We have put together a course that includes all the essential information you need to > work towards your goal. > > [**Get started**](/en-US/docs/Learn/Front-end_web_developer) ## Tutorials Our [CSS Learning Area](/en-US/docs/Learn/CSS) features multiple modules that teach CSS from the ground up — no previous knowledge required. - [CSS first steps](/en-US/docs/Learn/CSS/First_steps) - : CSS (Cascading Style Sheets) is used to style and layout web pages — for example, to alter the font, color, size, and spacing of your content, split it into multiple columns, or add animations and other decorative features. This module provides a gentle beginning to your path towards CSS mastery with the basics of how it works, what the syntax looks like, and how you can start using it to add styling to HTML. - [CSS building blocks](/en-US/docs/Learn/CSS/Building_blocks) - : This module carries on where [CSS first steps](/en-US/docs/Learn/CSS/First_steps) left off — now you've gained familiarity with the language and its syntax, and got some basic experience with using it, it's time to dive a bit deeper. This module looks at the cascade and inheritance, all the selector types we have available, units, sizing, styling backgrounds and borders, debugging, and lots more. The aim here is to provide you with a toolkit for writing competent CSS and help you understand all the essential theory, before moving on to more specific disciplines like [text styling](/en-US/docs/Learn/CSS/Styling_text) and [CSS layout](/en-US/docs/Learn/CSS/CSS_layout). - [CSS styling text](/en-US/docs/Learn/CSS/Styling_text) - : With the basics of the CSS language covered, the next CSS topic for you to concentrate on is styling text — one of the most common things you'll do with CSS. Here we look at text styling fundamentals, including setting font, boldness, italics, line and letter spacing, drop shadows, and other text features. We round off the module by looking at applying custom fonts to your page, and styling lists and links. - [CSS layout](/en-US/docs/Learn/CSS/CSS_layout) - : At this point we've already looked at CSS fundamentals, how to style text, and how to style and manipulate the boxes that your content sits inside. Now it's time to look at how to place your boxes in the right place in relation to the viewport, and to each other. We have covered the necessary prerequisites so we can now dive deep into CSS layout, looking at different display settings, modern layout tools like flexbox, CSS grid, and positioning, and some of the legacy techniques you might still want to know about. - [Use CSS to solve common problems](/en-US/docs/Learn/CSS/Howto) - : This module provides links to sections of content explaining how to use CSS to solve common problems when creating a web page. ## Reference - [CSS reference](/en-US/docs/Web/CSS/Reference): This exhaustive reference for seasoned Web developers describes every property and concept of CSS. - CSS key concepts: - The [syntax and forms of the language](/en-US/docs/Web/CSS/Syntax) - [Specificity](/en-US/docs/Web/CSS/Specificity), [inheritance](/en-US/docs/Web/CSS/Inheritance), and [the Cascade](/en-US/docs/Web/CSS/Cascade) - [CSS units and values](/en-US/docs/Web/CSS/CSS_Values_and_Units) and [functional notations](/en-US/docs/Web/CSS/CSS_Functions) - [Box model](/en-US/docs/Web/CSS/CSS_box_model/Introduction_to_the_CSS_box_model) and [margin collapse](/en-US/docs/Web/CSS/CSS_box_model/Mastering_margin_collapsing) - The [containing block](/en-US/docs/Web/CSS/Containing_block) - [Stacking](/en-US/docs/Web/CSS/CSS_positioned_layout/Understanding_z-index/Stacking_context) and [block-formatting](/en-US/docs/Web/CSS/CSS_display/Block_formatting_context) contexts - [Initial](/en-US/docs/Web/CSS/initial_value), [computed](/en-US/docs/Web/CSS/computed_value), [used](/en-US/docs/Web/CSS/used_value), and [actual](/en-US/docs/Web/CSS/actual_value) values - [CSS shorthand properties](/en-US/docs/Web/CSS/Shorthand_properties) - [CSS Flexible Box Layout](/en-US/docs/Web/CSS/CSS_flexible_box_layout) - [CSS Grid Layout](/en-US/docs/Web/CSS/CSS_grid_layout) - [CSS selectors](/en-US/docs/Web/CSS/CSS_selectors) - [Media queries](/en-US/docs/Web/CSS/CSS_media_queries) - [Animation](/en-US/docs/Web/CSS/animation) ## Cookbook The [CSS layout cookbook](/en-US/docs/Web/CSS/Layout_cookbook) aims to bring together recipes for common layout patterns, things you might need to implement in your sites. In addition to providing code you can use as a starting point in your projects, these recipes highlight the different ways layout specifications can be used and the choices you can make as a developer. ## Tools for CSS development - You can use the [W3C CSS Validation Service](https://jigsaw.w3.org/css-validator/) to check if your CSS is valid. This is an invaluable debugging tool. - [Firefox Developer Tools](https://firefox-source-docs.mozilla.org/devtools-user/index.html) lets you view and edit a page's live CSS via the [Inspector](https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/index.html) and [Style Editor](https://firefox-source-docs.mozilla.org/devtools-user/style_editor/index.html) tools. - The [Web Developer extension](https://addons.mozilla.org/en-US/firefox/addon/web-developer/) for Firefox lets you track and edit live CSS on watched sites. ## Meta bugs - Firefox: [Firefox bug 1323667](https://bugzil.la/1323667) ## See also - [CSS demos](/en-US/docs/Web/Demos#css): Get a creative boost by exploring examples of the latest CSS technologies in action. - Web languages to which CSS is often applied: [HTML](/en-US/docs/Web/HTML), [SVG](/en-US/docs/Web/SVG), [MathML](/en-US/docs/Web/MathML), {{Glossary("XHTML")}}, and [XML](/en-US/docs/Web/XML/XML_introduction). - [Stack Overflow questions about CSS](https://stackoverflow.com/questions/tagged/css)
0
data/mdn-content/files/en-us/web/css
data/mdn-content/files/en-us/web/css/scrollbar-gutter/index.md
--- title: scrollbar-gutter slug: Web/CSS/scrollbar-gutter page-type: css-property browser-compat: css.properties.scrollbar-gutter --- {{CSSRef}} The **`scrollbar-gutter`** [CSS](/en-US/docs/Web/CSS) property allows authors to reserve space for the scrollbar, preventing unwanted layout changes as the content grows while also avoiding unnecessary visuals when scrolling isn't needed. An element's _scrollbar gutter_ is the space between the inner border edge and the outer padding edge, where the browser may display a scrollbar. If no scrollbar is present, the gutter will be painted as an extension of the padding. The browser determines whether _classic_ scrollbars or _overlay_ scrollbars are used: - Classic scrollbars are always placed in a gutter, consuming space when present. - Overlay scrollbars are placed over the content, not in a gutter, and are usually partially transparent. ## Syntax ```css /* Initial value */ scrollbar-gutter: auto; /* "stable" keyword, with optional modifier */ scrollbar-gutter: stable; scrollbar-gutter: stable both-edges; /* Global values */ scrollbar-gutter: inherit; scrollbar-gutter: initial; scrollbar-gutter: revert; scrollbar-gutter: revert-layer; scrollbar-gutter: unset; ``` ### Values - `auto` - : The initial value. Classic scrollbars create a gutter when `overflow` is `scroll`, or when `overflow` is `auto` and the box is overflowing. Overlay scrollbars do not consume space. - `stable` - : When using classic scrollbars, the gutter will be present if `overflow` is `auto`, `scroll`, or `hidden` even if the box is not overflowing. When using overlay scrollbars, the gutter will not be present. - `both-edges` - : If a gutter would be present on one of the inline start/end edges of the box, another will be present on the opposite edge as well. ## Formal definition {{cssinfo}} ## Formal syntax {{csssyntax}} ## Examples The examples below show how the different values for the `scrollbar-gutter` property would affect a scrollable `div` element (`.container`) with one or more paragraphs contained within. > **Note:** In the images for the examples, the user's system settings are set to classic scrollbars (always shown). ### Example 1 Prevent unneeded layout changes as the content growing or shrinking causes the scrollbar to appear/disappear, a space is reserved for it. ```css .container { scrollbar-gutter: stable; } ``` ![A containing div element with a paragraph of text inside and a space to the right where the scrollbar is](stable-no-scroll.png) ### Example 2 Add symmetric spacing to both sides of the box so the content is centered: ```css .container { scrollbar-gutter: stable both-edges; } ``` ![A containing div element with a paragraph of text inside, a space to the right where the scrollbar is and a matching empty space to the left](stable-both-edges.png) ### Example 3 Align the contents of a non-scrolling element and a scrolling one adjacent to it: This example shows two divs side by side. The one on the left has no scroll, but the one on the right does. Both have `scrollbar-gutter` applied, which also reserves space for the div on the left which doesn't have scrollable content. This is a good technique to use to keep the width of content consistent. ```css .container1 { overflow: hidden; scrollbar-gutter: stable; } .container2 { scrollbar-gutter: stable; } ``` ![Two adjacent divs containing text, both with space for a scrollbar](side-by-side.png) ### Overlay scrollbars For reference, this image shows the same div as above, but with the user's system settings set to overlay scrollbars. Note here the scrollbar will only show when the user is scrolling and on top of the content, so no space is reserved for it and the `scrollbar-gutter` property has no effect. ![One div with text, no visible scrollbar](for-ref-no-scroll.png) ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [CSS overflow](/en-US/docs/Web/CSS/CSS_overflow) module - [CSS scrollbars styling](/en-US/docs/Web/CSS/CSS_scrollbars_styling) module - {{CSSxRef("overflow")}} - {{CSSxRef("scrollbar-width")}} - {{CSSxRef("scrollbar-color")}}
0
data/mdn-content/files/en-us/web/css
data/mdn-content/files/en-us/web/css/offset-position/index.md
--- title: offset-position slug: Web/CSS/offset-position page-type: css-property browser-compat: css.properties.offset-position --- {{CSSRef}} The **`offset-position`** [CSS](/en-US/docs/Web/CSS) property defines the initial position of an element along a path. This property is typically used in combination with the {{cssxref("offset-path")}} property to create a motion effect. The value of `offset-position` determines where the element gets placed initially for moving along an offset path if an `offset-path` function such as {{cssxref("path", "path()")}} does not specify its own starting position. The `offset-position` property is part of a motion system based on {{cssxref("offset")}} constituent properties, including {{cssxref("offset-anchor")}}, {{cssxref("offset-distance")}}, and `offset-path`. These properties work together to create various motion effects along a path. ## Syntax ```css /* Keyword values */ offset-position: normal; offset-position: auto; offset-position: top; offset-position: bottom; offset-position: left; offset-position: right; offset-position: center; /* <percentage> values */ offset-position: 25% 75%; /* <length> values */ offset-position: 0 0; offset-position: 1cm 2cm; offset-position: 10ch 8em; /* Edge offsets values */ offset-position: bottom 10px right 20px; offset-position: right 3em bottom 10px; offset-position: bottom 10px right; offset-position: top right 10px; /* Global values */ offset-position: inherit; offset-position: initial; offset-position: revert; offset-position: revert-layer; offset-position: unset; ``` ### Values - `normal` - : Indicates that the element does not have an offset starting position and places the element at `50% 50%` of the containing block. This is the default value. - `auto` - : Indicates that the offset starting position is the top-left corner of the element's box. - {{cssxref("&lt;position&gt;")}} - : Specifies the position as an x/y coordinate to place an element relative to its box edges. The position can be defined using one to four values. If two non-keyword values are used, the first value represents the horizontal position and the second represents the vertical position. If only one value is specified, the second value is assumed to be `center`. If three or four values are used, the {{cssxref("length-percentage")}} values are offsets for the preceding keyword value(s). For more explanation of these value types, see {{cssxref("background-position")}}. ## Formal definition {{cssinfo}} ## Formal syntax {{csssyntax}} ## Examples ### Setting initial offset-position for an offset-path In this example, the {{cssxref("offset-path")}} property is used to define the path along which the `cyan` element should move. The value of the {{cssxref("path")}} CSS function is an [SVG data path](/en-US/docs/Web/SVG/Attribute/d) that describes a curved path. The element moves along this curved path during the `move` animation. #### HTML ```html <div id="wrap"> <div id="motion-demo"></div> </div> ``` #### CSS ```css hidden #wrap { width: 260px; height: 160px; border: 1px dashed black; } ``` ```css #motion-demo { offset-path: path("M20,20 C20,100 200,0 200,100"); offset-position: left top; animation: move 3000ms infinite alternate ease-in-out; width: 40px; height: 40px; background: cyan; } @keyframes move { 0%, 20% { offset-distance: 0%; } 80%, 100% { offset-distance: 100%; } } ``` #### Result {{EmbedLiveSample('Setting_initial_offset_position_for_an_offset-path', '100%', 200)}} ### Comparing various offset starting positions This example visually compares various initial offset starting position of an element when {{cssxref("ray", "ray()")}} is used to specify a value for the {{cssxref("offset-path")}} property. The number inside the element box indicates the element to which CSS is applied as well as the element's anchor point. ```html hidden <div class="wrap"> <div class="box">0</div> <div class="box box0">0</div> <pre> offset-position: normal; /* No offset-path specified */ </pre> </div> <div class="wrap"> <div class="box">0</div> <div class="box box1">1</div> <pre> offset-position: normal; offset-path: ray(0deg); </pre> </div> <div class="wrap"> <div class="box">0</div> <div class="box box2">2</div> <pre> offset-position: auto; offset-path: ray(0deg); </pre> </div> <div class="wrap"> <div class="box">0</div> <div class="box box3">3</div> <pre> offset-position: left top; offset-path: ray(0deg); </pre> </div> <div class="wrap"> <div class="box">0</div> <div class="box box4">4</div> <pre> offset-position: 30% 70%; offset-path: ray(120deg); </pre> </div> ``` ```css hidden .wrap { position: relative; width: 80vw; height: 120px; border: 1px solid black; margin: 0 2em 4em 5em; text-align: center; } pre { font-size: 1em; text-align: right; padding-right: 10px; line-height: 1em; } .box { display: flex; justify-content: center; align-items: center; width: 50px; height: 50px; } .box + .box { opacity: 1; } ``` ```css .box { background-color: green; border-top: 6px dashed white; background-clip: border-box; position: absolute; top: 20px; left: 20px; opacity: 20%; color: white; } .box0 { offset-position: normal; } .box1 { offset-position: normal; offset-path: ray(0deg); } .box2 { offset-position: auto; offset-path: ray(0deg); } .box3 { offset-position: left top; offset-path: ray(0deg); } .box4 { offset-position: 30% 70%; offset-path: ray(120deg); } ``` #### Result {{EmbedLiveSample('Comparing various offset starting positions', '100%', 930)}} In `box0`, the absence of the `offset-path` property means that an `offset-position` of either `normal` or `auto` has no effect. When `offset-position` is `normal`, the ray starts at the center of the containing block (i.e., `50% 50%`). This is the default starting position of an offset path and is used when no `offset-position` is specified. Notice the difference between offset starting positions `auto` and `left top`. The value `auto` aligns the element's anchor point to its own top-left corner, whereas the value `left top` aligns the element's anchor point to the top-left corner of the containing block. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{cssxref("offset")}} - {{cssxref("offset-anchor")}} - {{cssxref("offset-distance")}} - {{cssxref("offset-path")}} - {{cssxref("offset-rotate")}}
0
data/mdn-content/files/en-us/web/css
data/mdn-content/files/en-us/web/css/rotate/index.md
--- title: rotate slug: Web/CSS/rotate page-type: css-property browser-compat: css.properties.rotate --- {{CSSRef}} The **`rotate`** [CSS](/en-US/docs/Web/CSS) property allows you to specify rotation transforms individually and independently of the {{CSSxRef("transform")}} property. This maps better to typical user interface usage, and saves having to remember the exact order of transform functions to specify in the `transform` property. {{EmbedInteractiveExample("pages/css/rotate.html")}} ## Syntax ```css /* Keyword values */ rotate: none; /* Angle value */ rotate: 90deg; rotate: 0.25turn; rotate: 1.57rad; /* x, y, or z axis name plus angle */ rotate: x 90deg; rotate: y 0.25turn; rotate: z 1.57rad; /* Vector plus angle value */ rotate: 1 1 1 90deg; /* Global values */ rotate: inherit; rotate: initial; rotate: revert; rotate: revert-layer; rotate: unset; ``` ### Values - angle value - : An {{CSSxRef("&lt;angle&gt;")}} specifying the angle to rotate the affected element through, around the Z axis. Equivalent to a `rotate()` (2D rotation) function. - x, y, or z axis name plus angle value - : The name of the axis you want to rotate the affected element around (`"x"`, "`y`", or "`z"`), plus an {{CSSxRef("&lt;angle&gt;")}} specifying the angle to rotate the element through. Equivalent to a `rotateX()`/`rotateY()`/`rotateZ()` (3D rotation) function. - vector plus angle value - : Three {{CSSxRef("&lt;number&gt;")}}s representing an origin-centered vector that defines a line around which you want to rotate the element, plus an {{CSSxRef("&lt;angle&gt;")}} specifying the angle to rotate the element through. Equivalent to a `rotate3d()` (3D rotation) function. - `none` - : Specifies that no rotation should be applied. ## Formal definition {{cssinfo}} ## Formal syntax {{csssyntax}} ## Examples ### Rotating an element on hover The following example shows how to use the `rotate` property to rotate an element along various axes on hover. The first box rotates 90 degrees on the Z axis hover, the second rotates 180 degrees on the Y axis on hover, and the third rotates 360 degrees on hover around a vector defined by coordinates. #### HTML ```html <div class="box" id="box1">rotate Z</div> <div class="box" id="box2">rotate Y</div> <div class="box" id="box3">vector & angle</div> ``` #### CSS ```css .box { display: inline-block; margin: 1em; min-width: 6.5em; line-height: 6.5em; text-align: center; transition: 1s ease-in-out; border: 0.25em dotted; } #box1:hover { rotate: 90deg; } #box2:hover { rotate: y 180deg; } #box3:hover { rotate: 1 2 1 360deg; } ``` #### Result {{EmbedLiveSample("Rotating_an_element_on_hover", "100%", 150)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{cssxref('translate')}} - {{cssxref('scale')}} - {{cssxref('transform')}} Note: `skew` is not an independent `transform` value
0
data/mdn-content/files/en-us/web/css
data/mdn-content/files/en-us/web/css/hue-interpolation-method/index.md
--- title: <hue-interpolation-method> slug: Web/CSS/hue-interpolation-method page-type: css-type browser-compat: - css.types.color.color-mix - css.types.image.gradient.conic-gradient.hue_interpolation_method - css.types.image.gradient.linear-gradient.hue_interpolation_method - css.types.image.gradient.radial-gradient.hue_interpolation_method - css.types.image.gradient.repeating-conic-gradient.hue_interpolation_method - css.types.image.gradient.repeating-linear-gradient.hue_interpolation_method - css.types.image.gradient.repeating-radial-gradient.hue_interpolation_method spec-urls: https://drafts.csswg.org/css-color/#hue-interpolation --- {{CSSRef}} The **`<hue-interpolation-method>`** [CSS](/en-US/docs/Web/CSS) [data type](/en-US/docs/Web/CSS/CSS_Types) represents the algorithm used for interpolation between {{CSSXref("&lt;hue&gt;")}} values. The interpolation method specifies how to find a midpoint between two hue values based on a color wheel. It is used as a component of the {{CSSXref("&lt;color-interpolation-method&gt;")}} data type. When interpolating `<hue>` values, the hue interpolation algorithm defaults to [`shorter`](#shorter). ## Syntax A `<hue-interpolation-method>` value consists of the name of a hue interpolation algorithm followed by a literal token `hue`: ```plain shorter hue longer hue increasing hue decreasing hue ``` ### Values Any pair of hue angles correspond to two radii on the {{Glossary("color wheel")}}, which cut the circumference into two possible arcs for interpolation. Both arcs start at the first radius and end at the second radius, but one goes clockwise and the other goes counterclockwise. > **Note:** The following descriptions and illustrations are based on color wheels in which hue angles increase in a clockwise direction. Be aware that there are color wheels where an increase in angles will be a counterclockwise operation. For a pair of hue angles `θ1` and `θ2` normalized to the range `[0deg, 360deg)`, there are four algorithms to determine which arc is used when interpolating from `θ1` to `θ2`: - `shorter` - : Use the shorter arc. When the two radii coincide, the arc degenerates to a single point. When both arcs have the same lengths: - If `θ1 < θ2`, use the clockwise arc; - If `θ1 > θ2`, use the counterclockwise arc. | `θ1 = 45deg`, `θ2 = 135deg` | `θ1 = 135deg`, `θ2 = 45deg` | | ------------------------------------------------------------------ | ------------------------------------------------------------------ | | ![shorter with θ1 = 45deg and θ2 = 135deg](shorter_increasing.png) | ![shorter with θ1 = 135deg and θ2 = 45deg](shorter_decreasing.png) | - `longer` - : Use the longer arc. When the two radii coincide: - If `θ1 ≤ θ2`, the arc becomes the full circumference with a clockwise orientation. - If `θ1 > θ2`, the arc becomes the full circumference with a counterclockwise orientation. When both arcs have the same lengths: - If `θ1 < θ2`, use the clockwise arc; - If `θ1 > θ2`, use the counterclockwise arc. | `θ1 = 45deg`, `θ2 = 135deg` | `θ1 = 135deg`, `θ2 = 45deg` | | ---------------------------------------------------------------- | ---------------------------------------------------------------- | | ![longer with θ1 = 45deg and θ2 = 135deg](longer_decreasing.png) | ![longer with θ1 = 135deg and θ2 = 45deg](longer_increasing.png) | - `increasing` - : Use the clockwise arc. When the two radii coincide, the arc degenerates to a single point. | `θ1 = 45deg`, `θ2 = 135deg` | `θ1 = 135deg`, `θ2 = 45deg` | | --------------------------------------------------------------------- | -------------------------------------------------------------------- | | ![increasing with θ1 = 45deg and θ2 = 135deg](shorter_increasing.png) | ![increasing with θ1 = 135deg and θ2 = 45deg](longer_increasing.png) | - `decreasing` - : Use the counterclockwise arc. When the two radii coincide, the arc degenerates to a single point. | `θ1 = 45deg`, `θ2 = 135deg` | `θ1 = 135deg`, `θ2 = 45deg` | | -------------------------------------------------------------------- | --------------------------------------------------------------------- | | ![decreasing with θ1 = 45deg and θ2 = 135deg](longer_decreasing.png) | ![decreasing with θ1 = 135deg and θ2 = 45deg](shorter_decreasing.png) | As there are only two arcs to choose from, these algorithms are pairwise equivalent under certain circumstances. Specifically: - If `0deg < θ2 - θ1 < 180deg` or `θ2 - θ1 < -180deg`, `shorter` and `increasing` are equivalent, whereas `longer` and `decreasing` are equivalent. - If `-180deg < θ2 - θ1 < 0deg` or `θ2 - θ1 > 180deg`, `shorter` and `decreasing` are equivalent, whereas `longer` and `increasing` are equivalent. A notable feature of `increasing` and `decreasing` is that when the hue angle difference passes through `180deg` during transition or animation, the arc will not flip to the other side like `shorter` and `longer` do. ## Formal syntax {{CSSSyntax}} ## Examples ### Comparing hue interpolation algorithms The following example shows the effect of using different hue interpolation algorithms in a {{CSSXref("gradient/linear-gradient", "linear-gradient()")}}. #### HTML ```html <div class="hsl"> <p>HSL</p> </div> <div class="hsl-increasing"> <p>HSL increasing</p> </div> <div class="hsl-decreasing"> <p>HSL decreasing</p> </div> <div class="hsl-shorter"> <p>HSL shorter</p> </div> <div class="hsl-longer"> <p>HSL longer</p> </div> <div class="hsl-named"> <p>HSL named</p> </div> <div class="hsl-named-longer"> <p>HSL named (longer)</p> </div> ``` #### CSS ```css hidden div { border: 1px solid black; height: 50px; margin: 10px; width: 90%; } p { color: white; margin: 6px; } /* Fallback styles */ .hsl, .hsl-shorter, .hsl-named { background: linear-gradient( to right, hsl(39 100% 50%), hsl(46 100% 50%), hsl(53 100% 50%), hsl(60 100% 50%) ); } .hsl-increasing { background: linear-gradient( to right, hsl(190 100% 50%), hsl(225 100% 50%), hsl(260 100% 50%), hsl(295 100% 50%), hsl(330 100% 50%), hsl(365 100% 50%), hsl(400 100% 50%), hsl(435 100% 50%), hsl(470 100% 50%), hsl(505 100% 50%), hsl(540 100% 50%) ); } .hsl-decreasing, .hsl-longer, .hsl-named-longer { background: linear-gradient( to right, hsl(399 100% 50%), hsl(368 100% 50%), hsl(337 100% 50%), hsl(307 100% 50%), hsl(276 100% 50%), hsl(245 100% 50%), hsl(214 100% 50%), hsl(183 100% 50%), hsl(152 100% 50%), hsl(122 100% 50%), hsl(91 100% 50%), hsl(60 100% 50%) ); } ``` ```css .hsl { background: linear-gradient( to right in hsl, hsl(39deg 100% 50%), hsl(60deg 100% 50%) ); } .hsl-increasing { background: linear-gradient( to right in hsl increasing hue, hsl(190deg 100% 50%), hsl(180deg 100% 50%) ); } .hsl-decreasing { background: linear-gradient( to right in hsl decreasing hue, hsl(39deg 100% 50%), hsl(60deg 100% 50%) ); } .hsl-shorter { background: linear-gradient( to right in hsl shorter hue, hsl(39deg 100% 50%), hsl(60deg 100% 50%) ); } .hsl-longer { background: linear-gradient( to right in hsl longer hue, hsl(39deg 100% 50%), hsl(60deg 100% 50%) ); } .hsl-named { background: linear-gradient(to right in hsl, orange, yellow); } .hsl-named-longer { background: linear-gradient(to right in hsl longer hue, orange, yellow); } ``` #### Result {{EmbedLiveSample("comparing_hue_interpolation_methods", "100%", 500)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{CSSXref("&lt;color-interpolation-method&gt;")}} - {{CSSXref("&lt;hue&gt;")}} data type
0
data/mdn-content/files/en-us/web/css
data/mdn-content/files/en-us/web/css/easing-function/index.md
--- title: <easing-function> slug: Web/CSS/easing-function page-type: css-type browser-compat: css.types.easing-function --- {{CSSRef}} The **`<easing-function>`** [CSS](/en-US/docs/Web/CSS) [data type](/en-US/docs/Web/CSS/CSS_Types) represents a mathematical function that describes the rate at which a value changes. This transition between two values may be applied in different situations. It may be used to describe how fast values change during animations. This lets you vary the animation's speed over the course of its duration. You can specify an easing function for CSS [transition](/en-US/docs/Web/CSS/transition-timing-function) and [animation](/en-US/docs/Web/CSS/animation-timing-function) properties. ## Syntax ```css /* linear function and keyword */ /* linear(<point-list>) */ linear(1, -0.5, 0) linear /* cubic-bezier function and keywords */ /* cubic-bezier(<x1>, <y1>, <x2>, <y2>) */ cubic-bezier(0.25, 0.1, 0.25, 1) ease ease-in ease-out ease-in-out /* steps function and keywords */ /* steps(<number-of-steps>, <direction>) */ steps(4, end) steps(10, jump-both) step-start step-end ``` ### Values - `linear` - : Specifies a constant rate of interpolation, with no change in the rate of progress throughout the duration (that is, no acceleration or deceleration). This keyword value is equivalent to both [`cubic-bezier(0, 0, 1, 1)`](#cubic_bézier_easing_function) and [`linear(0, 1)`](#linear_easing_function) functions. ![Graph of "Input progress" to "Output progress" showing a line extending from the origin to (1, 1).](linear.svg) - `<linear-easing-function>` - : Specifies a `linear()` function with one or more comma-separated _linear stops_, each containing up to two optional _stop lengths_, to control the progress of an animation or transition. The `linear()` function specifies a `<linear-stop-list>`, a comma-separated list of points along the animation or transition progress. Each point or `<linear-stop>` in the list is specified as a {{cssxref("&lt;number&gt;")}} between `0` and `1`. By default, each stop in the `<linear-stop-list>` is equidistant. To have more control on the progress of the animation or transition, each point can include up to two optional {{cssxref("&lt;percentage&gt;")}} `<linear-stop-length>` values. - `<number>`: Represents a point in time along the duration of the animation or transition. The value should be between `0` and `1`, where `0` represents the start of the iteration and `1` represents the end. - `<percentage>`: Indicates the position of a linear stop along the duration. It can take up to two values. If one value is specified, it defines the start of the associated linear stop. If two percentage values are specified, they define the length of the stop: the first percentage indicates the starting point and the second percentage indicates the ending point for that segment in the animation or transition. If no `<percentage>` value is specified, which is the default, the stops are spread evenly along the timeline. - `<cubic-bezier-easing-function>` - : Specifies a [Bézier curve](/en-US/docs/Glossary/Bezier_curve) to shape the progress of an animation or a transition. In CSS, Bézier curves are defined by four control points that mathematically describe the curve: a starting point, an ending point, and two control points. The cubic Bézier easing function can be defined in one of these two ways: by creating a custom curve with a four-parameter `cubic-bezier()` function call or by using one of the predefined keyword values, which map to the commonly used Bézier curve parameters. The predefined keyword values include: `ease`: This keyword represents the easing function `cubic-bezier(0.25, 0.1, 0.25, 1)`. It indicates that the interpolation starts slowly, accelerates sharply, and then slows gradually towards the end. It is similar to the `ease-in-out` keyword, though it accelerates more sharply at the beginning. `ease-in`: This keyword represents the easing function `cubic-bezier(0.42, 0, 1, 1)`. It indicates that the interpolation starts slowly, then progressively speeds up until the end, at which point it stops abruptly. `ease-out`: This keyword represents the easing function `cubic-bezier(0, 0, 0.58, 1)`. It indicates that the interpolation starts abruptly and then progressively slows down towards the end. `ease-in-out`: This keyword represents the easing function `cubic-bezier(0.42, 0, 0.58, 1)`. It indicates that the interpolation starts slowly, speeds up, and then slows down towards the end. At the beginning, it behaves like the `ease-in` keyword; at the end, it is like the `ease-out` keyword. ![Graphs of "Input progress" to "Output progress", of which "ease" shows a curved line quickly rising from the origin to (1, 1); "ease-in" shows a shallow curved line from the origin that straightens out as it approaches (1, 1); "ease-out" shows a straight diagonal line that slightly curves as it gets close to (1, 1); and "ease-in-out" shows a symmetrical, "S"-shaped line curving from the origin to (1, 1).](ease.svg) `cubic-bezier()`: This function accepts four {{cssxref("&lt;number&gt;")}} values to shape a curve. - {{cssxref("&lt;number&gt;")}}: Specifies the location of [P1 and P2 points](#cubic_bézier_easing_function) on the curve. `<x1>` and `<y1>` are the coordinates for point P1, and `<x2>` and `<y2>` are the coordinates for point P2. `<x1>` and `<x2>` values must be between `0` and `1`, otherwise the function will not work as expected. - `<step-easing-function>` - : Specifies a `steps()` function that divides the animation into a set number of equal-length intervals or "steps", causing the animation to jump from one step to the next rather than transitioning smoothly. This parameter accepts one of the following two keyword values that map to predefined `steps()` functions or a custom `steps()` function: `step-start`: This keyword represents the easing function `steps(1, jump-start)` or `steps(1, start)`. It indicates that the interpolation jumps immediately to its final state, where it stays until the end. `step-end`: This keyword represents the easing function `steps(1, jump-end)` or `steps(1, end)`. It indicates that the interpolation stays in its initial state until the end, at which point it jumps directly to its final state. ![Two graphs of "Input progress" to "Output progress". In the "step-start" graph, an unfilled circle represents the origin point (0,0), with a horizontal line extending from (0, 1) to (1, 1). In the "step-end" graph, a horizontal line extends from the origin to (1, 0), with an unfilled circle at (1,0) and a solid circle at (1, 1).](step.svg) `steps()`: This function accepts a positive {{cssxref("&lt;integer&gt;")}} and an optional `<step-position>`. - `<integer>`: Represents the number of equidistant intervals or 'steps'. It must be a positive integer greater than `0` unless the second parameter is `jump-none`, in which case, it must be a positive integer greater than `1`. - `<step-position>`: Specifies the [timing of the jump](#steps_easing_function) to occur either at the start, at the end, at both start and end, or at neither. The possible keyword values include: - `jump-start` denotes that the first jump occurs right at the start, essentially at the `0` point. No time is spent at the `0%` mark. - `jump-end` denotes that the last jump occurs right at the end, essentially at the `1` point. No time is spent at the `100%` mark. This is the default value when no `<step-position>` is specified. - `jump-none` denotes that no jump occurs either at the beginning or at the end, effectively removing a step during the duration. Instead, the progress holds steady at both the `0%` mark and `100%` marks. The duration of these holds is determined by dividing the total duration by the number of steps (1/n). - `jump-both` denotes that jumps occur at both the beginning and the end, essentially occurring at both the `0` and `1`. Effectively, a step is added at both the ends. No time is spent at the `0%` and `100%` marks. - `start` is the equivalent of `jump-start`. - `end` is the equivalent of `jump-end`. ## Description There are three types of easing functions: - [Linear](#linear_easing_function) - [Cubic Bézier](#cubic_bézier_easing_function) - [Steps](#steps_easing_function) ### Linear easing function The `linear()` function creates a piecewise linear easing, allowing the approximation of complex animations and transitions by interpolating linearly between the specified points. The interpolation occurs at a constant rate from beginning to end. A typical use of the `linear()` function is to provide many points to approximate any curve. For example, the `linear(0, 0.25, 1)` function has linear stops of `0`, `0.25`, and `1` as arguments. The animation or transition starts at point `0`, moves linearly to `0.25`, and then continues linearly to point `1`. Since no `<linear-stop-length>` percentage is specified, the same duration (50%) is used to go from `0` to `0.25` and from `0.25` to `1`. ![Graphs of "Input progress" to "Output progress", of which "linear(0, 0.25, 1)" shows a broken line connecting the origin, (0.5, 0.25), and (1, 1); and "linear(0, 0.25 75%, 1)" shows a broken line connecting the origin, (0.75, 0.25), and (1, 1).](linear_function.svg) By default, the stops are equidistant. So if there are 5 stops, they will be at 0%, 25%, 50%, 75%, and 100% of the duration. You can use optional `<linear-stop-length>` percentage values to provide finer control, defining the start and/or length of each segment, allowing for a more controlled progression of the transition. Consider an animation with a duration time of 100 seconds and a change of 100 pixels. Let's look at an example where the easing of the animation is specified: `linear(0, 0.25 75%, 1)`. In this case, the animation progresses to 25 pixels (25% of its total change) in the first 75 seconds (75% of the duration). The last 75 pixels are applied in the remaining 25 seconds of the animation. For the same animation, suppose the easing function is given instead as `linear(0, 0.5 25% 75%, 1)`. Here, the animation reaches 50 pixels (50% of its total change) in 25 seconds (25% of the duration) and remains there for 50 seconds (75% - 25% of the duration). Then the last 50 pixels are applied in the remaining 25 seconds of the duration. Note that `linear(0, 0.5 25% 75%, 1)` is equivalent to `linear(0, 0.5 25%, 0.5 75%, 1)`. > **Note:** The [`linear`](#linear) keyword is equivalent to the easing function `linear(0, 1)`. While the `linear` keyword is always interpreted as-is, the function `linear(0, 1)` gets interpreted as `linear(0 0%, 1 100%)`. ### Cubic Bézier easing function The `cubic-bezier()` functional notation defines a cubic [Bézier curve](/en-US/docs/Glossary/Bezier_curve). The easing functions in the cubic-bezier subset of easing functions are often called "smooth" easing functions because they can be used to smooth down the start and end of the {{Glossary("interpolation")}}. They correlate an input progress to an output progress, both expressed as {{cssxref("&lt;number&gt;")}}s. For these values, `0.0` represents the initial state, and `1.0` represents the final state. ![Graph of "Input progress" to "Output progress" showing an "S"-shaped line curving from the origin to (1, 1) with the Bezier control points P1(0.1, 0.6) and P2(0.7, 0.2).](cubic-bezier.svg) A cubic Bézier curve is defined by four points: P0, P1, P2, and P3. The points P0 and P3 represent the start and the end of the curve. In CSS, these points are fixed as the coordinates progress (the abscissa the input progress, the ordinate the output progress). P0 is `(0, 0)` and represents the initial progress and the initial state. P3 is `(1, 1)` and represents the final progress and the final state. Not all cubic Bézier curves are suitable as easing functions because not all are [mathematical functions](https://en.wikipedia.org/wiki/Function_%28mathematics%29); i.e., curves that for a given abscissa have zero or one value. With P0 and P3 fixed as defined by CSS, a cubic Bézier curve is a function, and is therefore valid, if and only if the abscissas of P1 and P2 are both in the `[0, 1]` range. Cubic Bézier curves with the P1 or P2 ordinate outside the `[0, 1]` range can cause the value to go farther than the final state and then return. In animations, for some properties, such as {{cssxref("left")}} or {{cssxref("right")}}, this creates a kind of "bouncing" effect. ![Graphs of the easing function "cubic-bezier(0.3, 0.2, 0.2, 1.4)", one of which shows the output progress going above 1 starting from a certain input progress, the other shows the output progress reaching and then staying at 1.](cubic-bezier_out_of_range.svg) However, certain properties will restrict the output if it goes outside an allowable range. For example, a color component greater than `255` or smaller than `0` in {{CSSXref("color_value/rgb", "rgb()")}} will be clipped to the closest allowed value (`255` and `0`, respectively). Some `cubic-bezier()` values exhibit this property. When you specify an invalid cubic Bézier curve, CSS ignores the whole property. Each of the keywords [`ease`](#ease), [`ease-in`](#ease-in), [`ease-out`](#ease-out), and [`ease-in-out`](#ease-in-out) is equivalent to a specific `cubic-bezier()` value. ### Steps easing function The `steps()` functional notation defines a [step function](https://en.wikipedia.org/wiki/Step_function) that divides the domain of output values in equidistant steps. This subclass of step functions are sometimes also called _staircase functions_. These are a few examples illustrating the `steps()` function: ```css steps(2, jump-start) /* Or steps(2, start) */ steps(4, jump-end) /* Or steps(4, end) */ steps(5, jump-none) steps(3, jump-both) ``` ![Graphs of "Input progress" to "Output progress", of which "steps(2, jump-start)" shows horizontal lines extending 0.5 unit from (0, 0.5) and (0.5, 1), respectively, with empty circles at the origin and (0.5, 0.5); "steps(4, jump-end)" shows horizontal lines extending 0.25 unit from (0, 0), (0.25, 0.25), (0.5, 0.5), and (0.75, 0.75), respectively, with unfilled circles at (0.25, 0), (0.5, 0.25), and (0.75, 0.5), and a solid circle at (1, 1); "steps(5, jump-none)" shows horizontal lines extending 0.2 unit from (0, 0), (0.2, 0.25), (0.4, 0.5), (0.6, 0.75), and (0.8, 1), respectively, with unfilled circles at (0.2, 0), (0.4, 0.25), (0.6, 0.5), and (0.8, 0.75); "steps(3, jump-both)" shows horizontal lines extending 1/3 unit from (0, 0.25), (1/3, 0.5), and (2/3, 0.75),respectively , with a solid circle at (1, 1) and unfilled circles at the origin, (1/3, 0.25), (2/3, 0.5), and (1, 0.75).](jump.svg) Each of the keywords [`step-start`](#step-start) and [`step-end`](#step-end) is equivalent to a specific `steps()` value. ## Formal syntax {{csssyntax}} ## Examples ### Comparing the easing functions This example provides an easy comparison between the different easing functions using an animation. From the drop-down menu, you can select an easing function – there are a couple of keywords and some `cubic-bezier()` and `steps()` options. After selecting an option, you can start and stop the animation using the provided button. #### HTML ```html <div> <div></div> </div> <ul> <li> <button class="animation-button">Start animation</button> </li> <li> <label for="easing-select">Choose an easing function:</label> <select id="easing-select"> <option selected>linear</option> <option>linear(0, 0.5 50%, 1)</option> <option>ease</option> <option>ease-in</option> <option>ease-in-out</option> <option>ease-out</option> <option>cubic-bezier(0.1, -0.6, 0.2, 0)</option> <option>cubic-bezier(0, 1.1, 0.8, 4)</option> <option>steps(5, end)</option> <option>steps(3, start)</option> <option>steps(4)</option> </select> </li> </ul> ``` #### CSS ```css body > div { position: relative; height: 100px; } div > div { position: absolute; width: 50px; height: 50px; background-color: blue; background-image: radial-gradient( circle at 10px 10px, rgb(25 255 255 / 80%), rgb(25 255 255 / 40%) ); border-radius: 50%; top: 25px; animation: 1.5s infinite alternate; } @keyframes move-right { from { left: 10%; } to { left: 90%; } } li { display: flex; align-items: center; justify-content: center; margin-bottom: 20px; } ``` #### JavaScript ```js const selectElem = document.querySelector("select"); const startBtn = document.querySelector("button"); const divElem = document.querySelector("div > div"); startBtn.addEventListener("click", () => { if (startBtn.textContent === "Start animation") { divElem.style.animationName = "move-right"; startBtn.textContent = "Stop animation"; divElem.style.animationTimingFunction = selectElem.value; } else { divElem.style.animationName = "unset"; startBtn.textContent = "Start animation"; } }); selectElem.addEventListener("change", () => { divElem.style.animationTimingFunction = selectElem.value; }); ``` #### Result {{EmbedLiveSample("comparing_the_easing_functions", "100%", 200)}} ### Using the cubic-bezier() function These cubic Bézier curves are valid for use in CSS: ```css example-good /* The canonical Bézier curve with four <number> in the [0,1] range */ cubic-bezier(0.1, 0.7, 1.0, 0.1) /* Using <integer> is valid because any <integer> is also a <number>. */ cubic-bezier(0, 0, 1, 1) /* Negative values for ordinates are valid, leading to bouncing effects. */ cubic-bezier(0.1, -0.6, 0.2, 0) /* Values greater than 1.0 for ordinates are also valid. */ cubic-bezier(0, 1.1, 0.8, 4) ``` These cubic Bézier curves definitions are invalid: ```css example-bad /* Though the animated output type may be a color, Bézier curves work with numerical ratios. */ cubic-bezier(0.1, red, 1.0, green) /* Abscissas must be in the [0, 1] range or the curve is not a function of time. */ cubic-bezier(2.45, 0.6, 4, 0.1) /* The two points must be defined, there is no default value. */ cubic-bezier(0.3, 2.1) /* Abscissas must be in the [0, 1] range or the curve is not a function of time. */ cubic-bezier(-1.9, 0.3, -0.2, 2.1) ``` ### Using the steps() function These easing functions are valid: ```css example-good /* There are 5 treads, the last one happens right before the end of the animation. */ steps(5, end) /* A two-step staircase, the first one happening at the start of the animation. */ steps(2, start) /* The second parameter is optional. */ steps(2) ``` > **Note:** If the animation contains multiple stops, then the steps specified in the `steps()` function will apply to each section. Therefore, an animation with three segments and `steps(2)` will contain 6 steps in total, 2 per segment. These easing functions are invalid: ```css example-bad /* The first parameter must be an <integer> and cannot be a real value, even if it is equal to one. */ steps(2.0, jump-end) /* The amount of steps must be non-negative. */ steps(-3, start) /* There must be at least one step. */ steps(0, jump-none) ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [CSS animations](/en-US/docs/Web/CSS/CSS_animations) - [CSS transitions](/en-US/docs/Web/CSS/CSS_transitions) - [cubic-bezier](https://cubic-bezier.com/) - [`linear()` easing generator](https://linear-easing-generator.netlify.app/)
0
data/mdn-content/files/en-us/web/css
data/mdn-content/files/en-us/web/css/easing-function/cubic-bezier_out_of_range.svg
<svg xmlns="http://www.w3.org/2000/svg" width="480" height="265"><style>text{font:12px sans-serif}</style><path fill="#fff" d="M0 0h480v265H0z"/><marker id="dot" markerHeight="5" markerWidth="5" viewBox="-2.5 -2.5 5 5"><circle r="2" fill="#00f"/></marker><marker id="tick" stroke-linecap="square" markerHeight="10" markerWidth="1" orient="auto" viewBox="-0.5 -0.5 1 10"><path stroke="#000" d="M0 0v9"/></marker><defs><g id="axes"><path stroke="#000" stroke-dasharray="5" d="M160-160H0M160-160V0"/><path stroke="#000" marker-mid="url(#tick)" marker-start="url(#tick)" d="M0-160v80V0"/><path stroke="#000" marker-end="url(#tick)" marker-mid="url(#tick)" d="M0 0h80 80"/><text x="-15" y="-160" dominant-baseline="mathematical" text-anchor="end">1</text><text x="-15" y="-80" dominant-baseline="mathematical" text-anchor="end">0.5</text><text x="-10" y="15" text-anchor="end">0</text><text x="80" y="25" text-anchor="middle">0.5</text><text x="160" y="25" text-anchor="middle">1</text><text x="-45" y="-80" text-anchor="middle" writing-mode="vertical-rl">Output progress</text><text x="80" y="40" text-anchor="middle">Input progress</text></g></defs><g id="example1" transform="translate(65 210)"><use href="#axes"/><path fill="none" stroke="#00f" stroke-width="3" marker-end="url(#dot)" marker-start="url(#dot)" d="M0 0c48-32 32-224 160-160"/></g><g id="example2" transform="translate(305 210)"><use href="#axes"/><path fill="none" stroke="#00f" stroke-dasharray="5" stroke-width="3" d="M78.4-160c18-15.4 43.4-19.1 81.6 0"/><path fill="none" stroke="#00f" stroke-width="3" marker-end="url(#dot)" marker-start="url(#dot)" d="M0 0c33.7-22.4 35.9-123.7 78.4-160H160"/></g><text x="240" y="25" style="font-size:16px" text-anchor="middle">cubic-bezier(0.3, 0.2, 0.2, 1.4)</text></svg>
0
data/mdn-content/files/en-us/web/css
data/mdn-content/files/en-us/web/css/easing-function/step.svg
<svg xmlns="http://www.w3.org/2000/svg" width="480" height="250"><style>text{font:12px sans-serif}.caption{font-size:16px}</style><path fill="#fff" d="M0 0h480v250H0z"/><marker id="dot" markerHeight="5" markerWidth="5" viewBox="-2.5 -2.5 5 5"><circle r="2" fill="#00f"/></marker><marker id="dot-hollow" markerHeight="5" markerWidth="5" viewBox="-2.5 -2.5 5 5"><circle r="1.5" fill="#fff" stroke="#00f"/></marker><marker id="tick" stroke-linecap="square" markerHeight="10" markerWidth="1" orient="auto" viewBox="-0.5 -0.5 1 10"><path stroke="#000" d="M0 0v9"/></marker><defs><g id="axes"><path stroke="#000" stroke-dasharray="5" d="M160-160H0M160-160V0"/><path stroke="#000" marker-mid="url(#tick)" marker-start="url(#tick)" d="M0-160v80V0"/><path stroke="#000" marker-end="url(#tick)" marker-mid="url(#tick)" d="M0 0h80 80"/><text x="-15" y="-160" dominant-baseline="mathematical" text-anchor="end">1</text><text x="-15" y="-80" dominant-baseline="mathematical" text-anchor="end">0.5</text><text x="-10" y="15" text-anchor="end">0</text><text x="80" y="25" text-anchor="middle">0.5</text><text x="160" y="25" text-anchor="middle">1</text><text x="-45" y="-80" text-anchor="middle" writing-mode="vertical-rl">Output progress</text><text x="80" y="40" text-anchor="middle">Input progress</text></g></defs><g id="step-start" transform="translate(65 195)"><use href="#axes"/><path stroke="#00f" stroke-dasharray="5" stroke-width="3" d="M0-160V0"/><path stroke-width="3" marker-end="url(#dot-hollow)" d="M0 0h0"/><path stroke="#00f" stroke-width="3" marker-end="url(#dot)" marker-start="url(#dot)" d="M0-160h160"/><text x="80" y="-175" class="caption" text-anchor="middle">step-start</text></g><g id="step-end" transform="translate(305 195)"><use href="#axes"/><path stroke="#00f" stroke-dasharray="5" stroke-width="3" d="M160-160V0"/><path stroke="#00f" stroke-width="3" marker-end="url(#dot-hollow)" marker-start="url(#dot)" d="M0 0h160"/><path stroke-width="3" marker-start="url(#dot)" d="M160-160h0"/><text x="80" y="-175" class="caption" text-anchor="middle">step-end</text></g></svg>
0
data/mdn-content/files/en-us/web/css
data/mdn-content/files/en-us/web/css/easing-function/jump.svg
<svg xmlns="http://www.w3.org/2000/svg" width="480" height="500"><style>text{font:12px sans-serif}.caption{font-size:16px}</style><path fill="#fff" d="M0 0h480v500H0z"/><marker id="dot" markerHeight="5" markerWidth="5" viewBox="-2.5 -2.5 5 5"><circle r="2" fill="#00f"/></marker><marker id="dot-hollow" markerHeight="5" markerWidth="5" viewBox="-2.5 -2.5 5 5"><circle r="1.5" fill="#fff" stroke="#00f"/></marker><marker id="tick" stroke-linecap="square" markerHeight="10" markerWidth="1" orient="auto" viewBox="-0.5 -0.5 1 10"><path stroke="#000" d="M0 0v9"/></marker><defs><g id="axes"><path stroke="#000" stroke-dasharray="5" d="M160-160H0M160-160V0"/><path stroke="#000" marker-mid="url(#tick)" marker-start="url(#tick)" d="M0-160v80V0"/><path stroke="#000" marker-end="url(#tick)" marker-mid="url(#tick)" d="M0 0h80 80"/><text x="-15" y="-160" dominant-baseline="mathematical" text-anchor="end">1</text><text x="-15" y="-80" dominant-baseline="mathematical" text-anchor="end">0.5</text><text x="-10" y="15" text-anchor="end">0</text><text x="80" y="25" text-anchor="middle">0.5</text><text x="160" y="25" text-anchor="middle">1</text><text x="-45" y="-80" text-anchor="middle" writing-mode="vertical-rl">Output progress</text><text x="80" y="40" text-anchor="middle">Input progress</text></g></defs><g id="jump-start" transform="translate(65 195)"><use href="#axes"/><path stroke="#00f" stroke-dasharray="5" stroke-width="3" d="M0-80V0m80-160v80"/><path stroke-width="3" marker-end="url(#dot-hollow)" d="M0 0h0"/><path stroke="#00f" stroke-width="3" marker-end="url(#dot-hollow)" marker-start="url(#dot)" d="M0-80h80"/><path stroke="#00f" stroke-width="3" marker-end="url(#dot)" marker-start="url(#dot)" d="M80-160h80"/><text x="80" y="-175" class="caption" text-anchor="middle">steps(2, jump-start)</text></g><g id="jump-end" transform="translate(305 195)"><use href="#axes"/><path stroke="#00f" stroke-dasharray="5" stroke-width="3" d="M40-40V0m40-80v40m40-80v40m40-80v40"/><path stroke="#00f" stroke-width="3" marker-end="url(#dot-hollow)" marker-start="url(#dot)" d="M0 0h40"/><path stroke="#00f" stroke-width="3" marker-end="url(#dot-hollow)" marker-start="url(#dot)" d="M40-40h40"/><path stroke="#00f" stroke-width="3" marker-end="url(#dot-hollow)" marker-start="url(#dot)" d="M80-80h40"/><path stroke="#00f" stroke-width="3" marker-end="url(#dot-hollow)" marker-start="url(#dot)" d="M120-120h40"/><path stroke="#00f" stroke-width="3" marker-start="url(#dot)" d="M160-160"/><text x="80" y="-175" class="caption" text-anchor="middle">steps(4, jump-end)</text></g><g id="jump-none" transform="translate(65 445)"><use href="#axes"/><path stroke="#00f" stroke-dasharray="5" stroke-width="3" d="M32-40V0m32-80v40m32-80v40m32-80v40"/><path stroke="#00f" stroke-width="3" marker-end="url(#dot-hollow)" marker-start="url(#dot)" d="M0 0h32"/><path stroke="#00f" stroke-width="3" marker-end="url(#dot-hollow)" marker-start="url(#dot)" d="M32-40h32"/><path stroke="#00f" stroke-width="3" marker-end="url(#dot-hollow)" marker-start="url(#dot)" d="M64-80h32"/><path stroke="#00f" stroke-width="3" marker-end="url(#dot-hollow)" marker-start="url(#dot)" d="M96-120h32"/><path stroke="#00f" stroke-width="3" marker-end="url(#dot)" marker-start="url(#dot)" d="M128-160h32"/><text x="80" y="-175" class="caption" text-anchor="middle">steps(5, jump-none)</text></g><g id="jump-both" transform="translate(305 445)"><use href="#axes"/><path stroke="#00f" stroke-dasharray="5" stroke-width="3" d="M0-40V0m53.3-80v40m53.4-80v40m53.3-80v40"/><path stroke="#00f" stroke-width="3" marker-end="url(#dot-hollow)" d="M0 0h0"/><path stroke="#00f" stroke-width="3" marker-end="url(#dot-hollow)" marker-start="url(#dot)" d="M0-40h53.3"/><path stroke="#00f" stroke-width="3" marker-end="url(#dot-hollow)" marker-start="url(#dot)" d="M53.3-80h53.4"/><path stroke="#00f" stroke-width="3" marker-end="url(#dot-hollow)" marker-start="url(#dot)" d="M106.7-120H160"/><path stroke="#00f" stroke-width="3" marker-start="url(#dot)" d="M160-160"/><text x="80" y="-175" class="caption" text-anchor="middle">steps(3, jump-both)</text></g></svg>
0
data/mdn-content/files/en-us/web/css
data/mdn-content/files/en-us/web/css/easing-function/linear_function.svg
<svg xmlns="http://www.w3.org/2000/svg" width="480" height="250"><style>text{font:12px sans-serif}.caption{font-size:16px}</style><path fill="#fff" d="M0 0h480v250H0z"/><marker id="dot" markerHeight="5" markerWidth="5" viewBox="-2.5 -2.5 5 5"><circle r="2" fill="#00f"/></marker><marker id="tick" stroke-linecap="square" markerHeight="10" markerWidth="1" orient="auto" viewBox="-0.5 -0.5 1 10"><path stroke="#000" d="M0 0v9"/></marker><defs><g id="axes"><path stroke="#000" stroke-dasharray="5" d="M160-160H0M160-160V0"/><path stroke="#000" marker-mid="url(#tick)" marker-start="url(#tick)" d="M0-160v80V0"/><path stroke="#000" marker-end="url(#tick)" marker-mid="url(#tick)" d="M0 0h80 80"/><text x="-15" y="-160" dominant-baseline="mathematical" text-anchor="end">1</text><text x="-15" y="-80" dominant-baseline="mathematical" text-anchor="end">0.5</text><text x="-10" y="15" text-anchor="end">0</text><text x="80" y="25" text-anchor="middle">0.5</text><text x="160" y="25" text-anchor="middle">1</text><text x="-45" y="-80" text-anchor="middle" writing-mode="vertical-rl">Output progress</text><text x="80" y="40" text-anchor="middle">Input progress</text></g></defs><g id="example1" transform="translate(65 195)"><use href="#axes"/><path fill="none" stroke="#00f" stroke-width="3" marker-end="url(#dot)" marker-mid="url(#dot)" marker-start="url(#dot)" d="m0 0 80-40 80-120"/><text x="80" y="-175" class="caption" text-anchor="middle">linear(0, 0.25, 1)</text></g><g id="example2" transform="translate(305 195)"><use href="#axes"/><path fill="none" stroke="#00f" stroke-width="3" marker-end="url(#dot)" marker-mid="url(#dot)" marker-start="url(#dot)" d="m0 0 120-40 40-120"/><text x="80" y="-175" class="caption" text-anchor="middle">linear(0, 0.25 75%, 1)</text></g></svg>
0
data/mdn-content/files/en-us/web/css
data/mdn-content/files/en-us/web/css/easing-function/ease.svg
<svg xmlns="http://www.w3.org/2000/svg" width="480" height="500"><style>text{font:12px sans-serif}.caption{font-size:16px}</style><path fill="#fff" d="M0 0h480v500H0z"/><marker id="dot" markerHeight="5" markerWidth="5" viewBox="-2.5 -2.5 5 5"><circle r="2" fill="#00f"/></marker><marker id="tick" stroke-linecap="square" markerHeight="10" markerWidth="1" orient="auto" viewBox="-0.5 -0.5 1 10"><path stroke="#000" d="M0 0v9"/></marker><defs><g id="axes"><path stroke="#000" stroke-dasharray="5" d="M160-160H0M160-160V0"/><path stroke="#000" marker-mid="url(#tick)" marker-start="url(#tick)" d="M0-160v80V0"/><path stroke="#000" marker-end="url(#tick)" marker-mid="url(#tick)" d="M0 0h80 80"/><text x="-15" y="-160" dominant-baseline="mathematical" text-anchor="end">1</text><text x="-15" y="-80" dominant-baseline="mathematical" text-anchor="end">0.5</text><text x="-10" y="15" text-anchor="end">0</text><text x="80" y="25" text-anchor="middle">0.5</text><text x="160" y="25" text-anchor="middle">1</text><text x="-45" y="-80" text-anchor="middle" writing-mode="vertical-rl">Output progress</text><text x="80" y="40" text-anchor="middle">Input progress</text></g></defs><g id="ease" transform="translate(65 195)"><use href="#axes"/><path fill="none" stroke="#00f" stroke-width="3" marker-end="url(#dot)" marker-start="url(#dot)" d="M0 0c40-16 92.8-160 160-160"/><text x="80" y="-175" class="caption" text-anchor="middle">ease</text></g><g id="ease-in" transform="translate(305 195)"><use href="#axes"/><path fill="none" stroke="#00f" stroke-width="3" marker-end="url(#dot)" marker-start="url(#dot)" d="M0 0c67.2 0 160-160 160-160"/><text x="80" y="-175" class="caption" text-anchor="middle">ease-in</text></g><g id="ease-out" transform="translate(65 445)"><use href="#axes"/><path fill="none" stroke="#00f" stroke-width="3" marker-end="url(#dot)" marker-start="url(#dot)" d="M0 0s92.8-160 160-160"/><text x="80" y="-175" class="caption" text-anchor="middle">ease-out</text></g><g id="ease-in-out" transform="translate(305 445)"><use href="#axes"/><path fill="none" stroke="#00f" stroke-width="3" marker-end="url(#dot)" marker-start="url(#dot)" d="M0 0c67.2 0 92.8-160 160-160"/><text x="80" y="-175" class="caption" text-anchor="middle">ease-in-out</text></g></svg>
0
data/mdn-content/files/en-us/web/css
data/mdn-content/files/en-us/web/css/easing-function/cubic-bezier.svg
<svg xmlns="http://www.w3.org/2000/svg" width="290" height="250" viewBox="-65 -195 290 250"><style>text{font:12px sans-serif}.sub{font-size:8px}</style><path fill="#fff" d="M-65-195h290V55H-65z"/><marker id="dot" markerHeight="5" markerWidth="5" viewBox="-2.5 -2.5 5 5"><circle r="2" fill="#00f"/></marker><marker id="dot-hollow" markerHeight="5" markerWidth="5" viewBox="-2.5 -2.5 5 5"><circle r="1.5" fill="#fff" stroke="red"/></marker><marker id="tick" stroke-linecap="square" markerHeight="10" markerWidth="1" orient="auto" viewBox="-0.5 -0.5 1 10"><path stroke="#000" d="M0 0v9"/></marker><path stroke="#000" stroke-dasharray="5" d="M160-160H0M160-160V0"/><path stroke="#000" marker-mid="url(#tick)" marker-start="url(#tick)" d="M0-160v80V0"/><path stroke="#000" marker-end="url(#tick)" marker-mid="url(#tick)" d="M0 0h80 80"/><text x="-15" y="-160" dominant-baseline="mathematical" text-anchor="end">1</text><text x="-15" y="-80" dominant-baseline="mathematical" text-anchor="end">0.5</text><text x="80" y="25" text-anchor="middle">0.5</text><text x="160" y="25" text-anchor="middle">1</text><text x="-45" y="-80" text-anchor="middle" writing-mode="vertical-rl">Output progress</text><text x="80" y="40" text-anchor="middle">Input progress</text><path stroke="red" stroke-dasharray="5" stroke-width="2" marker-end="url(#dot-hollow)" d="m0 0 16-96"/><path stroke="red" stroke-dasharray="5" stroke-width="2" marker-end="url(#dot-hollow)" d="M160-160 112-32"/><path fill="none" stroke="#00f" stroke-width="3" marker-end="url(#dot)" marker-start="url(#dot)" d="M0 0c16-96 112-32 160-160"/><text y="20" text-anchor="middle">P<tspan class="sub">0</tspan>(0, 0)</text><text x="5" y="-105">P<tspan class="sub">1</tspan>(0.1, 0.6)</text><text x="112" y="-15" text-anchor="middle">P<tspan class="sub">2</tspan>(0.7, 0.2)</text><text x="170" y="-160" dominant-baseline="mathematical">P<tspan class="sub">3</tspan>(1, 1)</text><text x="80" y="-175" style="font-size:16px" text-anchor="middle">cubic-bezier(0.1, 0.6, 0.7, 0.2)</text></svg>
0
data/mdn-content/files/en-us/web/css
data/mdn-content/files/en-us/web/css/easing-function/linear.svg
<svg xmlns="http://www.w3.org/2000/svg" width="240" height="250" viewBox="-65 -195 240 250"><style>text{font:12px sans-serif}</style><path fill="#fff" d="M-65-195h240V55H-65z"/><marker id="dot" markerHeight="5" markerWidth="5" viewBox="-2.5 -2.5 5 5"><circle r="2" fill="#00f"/></marker><marker id="tick" stroke-linecap="square" markerHeight="10" markerWidth="1" orient="auto" viewBox="-0.5 -0.5 1 10"><path stroke="#000" d="M0 0v9"/></marker><path stroke="#000" stroke-dasharray="5" d="M160-160H0M160-160V0"/><path stroke="#000" marker-mid="url(#tick)" marker-start="url(#tick)" d="M0-160v80V0"/><path stroke="#000" marker-end="url(#tick)" marker-mid="url(#tick)" d="M0 0h80 80"/><text x="-15" y="-160" dominant-baseline="mathematical" text-anchor="end">1</text><text x="-15" y="-80" dominant-baseline="mathematical" text-anchor="end">0.5</text><text x="-10" y="15" text-anchor="end">0</text><text x="80" y="25" text-anchor="middle">0.5</text><text x="160" y="25" text-anchor="middle">1</text><text x="-45" y="-80" text-anchor="middle" writing-mode="vertical-rl">Output progress</text><text x="80" y="40" text-anchor="middle">Input progress</text><path stroke="#00f" stroke-width="3" marker-end="url(#dot)" marker-start="url(#dot)" d="m0 0 160-160"/><text x="80" y="-175" style="font-size:16px" text-anchor="middle">linear</text></svg>
0