Operable - Accessibility

Operable
========

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.

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.

| Success criteria | How to conform to the criteria | Practical resource |
| --- | --- | --- |
| 2.1.1 Keyboard (A) |
 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.
  |
 See
 UI controls
 and
 Building keyboard accessibility back in |
| 2.1.2 No keyboard trap (A) |
 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 `Enter`/`Return`
 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.

 This is very important so that keyboard users do not get trapped on
 specific sections of your apps.
  |  |
| 2.1.3 Keyboard — all functionality (AAA) |
 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.
  |
 See
 UI controls
 and
 Building keyboard accessibility back in |
|
 2.1.4 Character Key Shortcuts (A)
 *added in 2.1* |
 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.
  | Understanding Character Key Shortcuts |

**Note:** Also see the WCAG description for Guideline 2.1 Keyboard Accessible: Make all functionality available from a keyboard.

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.

| Success criteria | How to conform to the criteria | Practical resource |
| --- | --- | --- |
| 2.2.1 Timing is adjustable (A) |
 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.

 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.
  |  |
| 2.2.2 Pausing, stopping, hiding (A) |
 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.

 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.
  |  |
| 2.2.3 No time limits (AAA) |
 This builds on criteria 2.2.1, stating that content that wants to pass
 AAA conformance should have no time limits.
  |  |
| 2.2.4 Suppress interruptions (AAA) |
 Any interruptions such as alerts or interstitial adverts should have
 functionality available to suppress or postpone them, unless it is an
 emergency alert.
  |  |
| 2.2.5 Re-authenticating (AAA) |
 If an authentication session expires during usage of a web app, the user
 can re-authenticate and continue their usage without losing any data.
  |  |
|
 2.2.6 Timeouts (AAA)
 *added in 2.1* |
 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).
  | Understanding Timeouts |

**Note:** Also see the WCAG description for Guideline 2.2 Enough Time: Provide users enough time to read and use content.

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.

| Success criteria | How to conform to the criteria | Practical resource |
| --- | --- | --- |
| 2.3.1 Three flashes, or below threshold (A) | Content doesn't contain any aspect that Flashes more than three times per second, or flashing content is below acceptable flash and red flash thresholds. |  |
| 2.3.2 Three flashes (AAA) | Content doesn't contain any aspect that Flashes more than three times per second. |  |
| 2.3.3 Animations from Interactions (AAA) *added in 2.1* | Allow users to disable animations from interactions (unless the animation is essential). | Understanding Animations from Interactions |

**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.

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.

| Success criteria | How to conform to the criteria | Practical resource |
| --- | --- | --- |
| 2.4.1 Bypass blocks (A) |
 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.

 If a proper structure of headings and semantic containers is provided
 to navigate with (for example `<section>`,
 `<aside>`, etc.), then an added "skip link" is
 not needed.
  | *Need to add a section on "skip links".* |
| 2.4.2 Include page title (A) |
 Each web page should include an informative
 `<title>`, the content of which describes the
 page's content/purpose.
  |
 See
 Adding a title.
  |
| 2.4.3 Logical focus order (A) |
 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.
  |
 See
 UI controls
 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
 positioning
 to handle the layout.
  |
| 2.4.4 Link purpose (in context) (A) |
 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 *all* users (see
 ambiguous to users in general
 for a useful explanation of this).
  |
 See
 Meaningful text labels. 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.
  |
| 2.4.5 Multiple navigation mechanisms (AA) |
 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.

 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.
  |
 Most of these mechanisms can be created using simple HTML features, for
 example see
 Search field,
 Creating a navigation menu,
 Styling links as buttons.
  |
| 2.4.6 Headings and labels (AA) |
 Heading (e.g. <h2>) and
 `<label>` elements clearly describe the purpose
 of the content and form elements they are supposed to be describing.
  |
 See
 UI controls,
 Meaningful text labels,
 The basics of headings and paragraphs,
 The <label> element.

 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.
  |
| 2.4.7 Visible focus for focusable elements (AA) |
 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.
  |
 See
 Using native keyboard accessibility.
  |
| 2.4.8 Location within site (AAA) |
 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".
  |  |
| 2.4.9 Link purpose (link only) (AAA) |
 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.
  |
 See
 Meaningful text labels. 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.
  |
| 2.4.10 Section headings (AAA) |
 As well as creating a useful document structure, headings should also
 accurately describe and break up content areas into logical sections.

 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.
  |
 See
 The basics of headings and paragraphs.
  |
| 2.4.11 Focus not obscured (Minimum) (AA) | When a user interface component receives keyboard focus, the component is not entirely hidden due to containing author-created content.
**Note:** 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. | Check out Understanding focus not obscured (Minimum) to learn more about this standard. |
| 2.4.12 Focus not obscured (Enhanced) (AAA) | 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. | Check out Understanding focus not obscured (Enhanced) (Level AAA) to learn more about this standard. |
| 2.4.13 Focus appearance (AAA) | When the keyboard focus indicator is visible, the area of the focus indicator meets all the following:* Must be at least as large as the area of a `2px` thick perimeter of the unfocused component or sub-component, which includes component's content, border, and background, excluding outer shadows or glow effects.
* Needs to have a contrast ratio of at least 3:1 between the same pixels in the focused and unfocused states

The exceptions to this are:* The focus indicator is determined by the user and cannot be adjusted by the author.
* The focus indicator and the indicator's background color are not modified by the author.
 | Check out Understanding focus appearance (Level AAA) to learn more about this standard. |

**Note:** Also see the WCAG description for Guideline 2.4 Navigable: Provide ways to help users navigate, find content, and determine where they are.

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).

| Success criteria | How to conform to the criteria | Practical resource |
| --- | --- | --- |
| 2.5.1 Pointer Gestures (A) *added in 2.1* | 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. | Understanding Pointer Gestures |
| 2.5.2 Pointer Cancellation (A) *added in 2.1* | 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. | Understanding Pointer Cancellation |
| 2.5.3 Label in Name (A) *added in 2.1* | 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. | Understanding Label in Name |
| 2.5.4 Motion Actuation (A) *added in 2.1* | 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. | Understanding Motion Actuation |
| 2.5.5 Target Size (AAA) *added in 2.1* | The size of an actionable item's touch target must be at least 44 CSS pixels in both width and height. Exceptions exist. | Understanding Target Size |
| 2.5.6 Concurrent Input Mechanisms (AAA) *added in 2.1* | 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. | Understanding Concurrent Input Mechanism |
| 2.5.8 Target size minimum (AA) | Target size for pointer inputs should be at least `24px` wide by `24px` tall except for the following areas:
 * **Spacing:**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.
* **Equivalent:** A separate control that achieves the same function that meets this standard is available on the same page.
* **Inline:** The target is located within a line of text with its size constrained by the line height or surrounding non-target text.
* **User agent control:** The target's size is determined by the user agent and has not been modified by the author.
* **Essential:** A particular presentation of the target is essential or legally required for the information being conveyed.
 | Check out Understanding target size minimum |

**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.

See also
--------

* WCAG
    1. Perceivable
    2. Operable
    3. Understandable
    4. Robust


Understandable - Accessibility

Understandable
==============

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.

Guideline 3.1 — Readable: Make text content readable and understandable
-----------------------------------------------------------------------

This guideline focuses on making text content as understandable as possible.

| Success criteria | How to conform to the criteria | Practical resource |
| --- | --- | --- |
| 3.1.1 Language of Page (A) |
 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 lang
 attribute on the page's `<html>` element, giving
 it a value equal to the language code that best represents the language
 the page is written in.
  |
 See
 Setting the primary language of the document.
  |
| 3.1.2 Language of Parts (AA) |
 In cases where the content of a page includes words or phrases that
 are in a different language to the primary language, use the
 lang attribute on an element wrapped
 around the term in question (e.g. a `<span>`
 if no semantic element is available) to set an appropriate language
 for it.

 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).
  |  |
| 3.1.3 Unusual Words (AAA) |
 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
 description list
 at the bottom of the page.
  |  |
| 3.1.4 Abbreviations (AAA) |
 Where abbreviations are used, you should provide an expansion of them,
 or a definition as required.

 The `<abbr>` element is often thought of as
 the preferred way to provide an expansion for an abbreviation — it
 takes a title 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.
  |
 See
 Abbreviations.
  |
| 3.1.5 Reading Level (AAA) |
 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.

 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).
  |  |
| 3.1.6 Pronunciation (AAA) |
 A mechanism should be provided to give users access to pronunciation
 of words where they are is needed to understand the content fully.

 The HTML `<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.
  |
 See
 Video and audio content, and
 Pronunciation Guide for English Dictionary |

**Note:** Also see the WCAG description for Guideline 3.1 Readable: Make text content readable and understandable.

Guideline 3.2 — Predictable: Make Web pages appear and operate in predictable ways
----------------------------------------------------------------------------------

This guideline focuses on making user interfaces intuitive and understandable.

| Success criteria | How to conform to the criteria | Practical resource |
| --- | --- | --- |
| 3.2.1 On Focus (A) |
 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.

 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.
  | `Element.focus_event` contains some
 useful information. Also see
 Building keyboard accessibility back in
 for some useful implementation ideas.
  |
| 3.2.2 On Input (A) |
 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.

 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.
  | The `input` event is useful here. |
| 3.2.3 Consistent Navigation (AA) |
 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.

 Again, sensible design — make the navigation controls the same across
 all pages or views.
  |
 See
 Page layouts
 for information on modern markup for layouts. See also
 Styling links as buttons
 for a useful accessible navigation menu example.
  |
| 3.2.4 Consistent Identification (AA) |
 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.

Again, sensible design! |
 "Labels" can refer to descriptive information in text content, or HTML
 form labels. See
 Meaningful text labels
 for more information.
  |
| 3.2.5 Change on Request (AAA) |
 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.

 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...)

 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.
  |
| 3.2.6 Consistent help (A) | 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. | Check out the consistent help documentation for this standard to learn more. |
|

**Note:** Also see the WCAG description for Guideline 3.2 Predictable: Make Web pages appear and operate in predictable ways.

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.

| Success criteria | How to conform to the criteria | Practical resource |
| --- | --- | --- |
| 3.3.1 Error Identification (A) |
 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.

 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.

**Note**: 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.

 |
 See
 Form data validation
 for comprehensive validation information, and
 WAI-ARIA: Dynamic content updates
 for information on live regions.
  |
| 3.3.2 Labels or Instructions (A) |
 Clear instructions should be provided when data input is required.
 When a simple instruction or prompt is required, you can use
 `<label>` elements for single inputs like name
 or age, a combination or `<label>`s and
 `<fieldset>`s/`<legend>`s
 for multiple inputs that go together (like the elements of a date of
 birth or postal address).

 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.
  | * Meaningful text labels
* How to structure an HTML form
* Text labels and names
 |
| 3.3.3 Error Suggestion (AA) |
 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).

 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).
  | No tutorial suggestions yet. |
| 3.3.4 Error Prevention (Legal, Financial, Data) (AA) |
 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:
 * Submissions are reversible.
* Data is checked for errors, and the user is given an opportunity to
 correct them.
* A mechanism is available for confirming and correcting information
 before final submission.
 |
**Reversible** — 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
 Django web framework).

**Checking data** — 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.

**Confirm and correct** — 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.
  |
| 3.3.5 Context-sensitive help is available (AAA) |
 Provide instructions and other appropriate cues in context to aid form
 completion and submission.
  |
 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.
  |
| 3.3.6 Error Prevention (All) (AAA) |
 This principle builds on 3.3.4, extending its requirements to all user
 input situations, not just ones involving sensitive data.
  | Again, see 3.3.4. |
| 3.3.7 Redundant entry (A) | 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. | Check out Understanding redundant entry to learn more. |
| 3.3.8 Accessible authentication (Minimum) (AA) | 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). | Check out the accessible authentication documentation for this standard to learn more. |
| 3.3.9 Accessible Authentication (Enhanced) (AAA) | 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. | Check out the enhanced accessible authentication documentation (AAA) to learn more. |

**Note:** Also see the WCAG description for Guideline 3.3 Input Assistance: Help users avoid and correct mistakes.

See also
--------

* WCAG
    1. Perceivable
    2. Operable
    3. Understandable
    4. Robust


Keyboard - Accessibility

Keyboard
========

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 global HTML attribute
* Element: keydown event
* 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 global HTML attribute
* Understanding focus order
* Don't use tabindex greater than 0
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 global HTML attribute
* Element: keydown event
* 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
* 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 `Tab` key, in the sequence of such elements as defined in the HTML document.

### See also

* 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` and `: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


Robust - Accessibility

Robust
======

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.

**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.

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.

| Success criteria | How to conform to the criteria | Practical resource |
| --- | --- | --- |
| 4.1.1 Parsing (A) |
 Content should be well-formed so it can be parsed successfully by
 browsers and other user agents such as screen readers.

 To pass this criterion, make sure that your HTML is as valid as
 possible. Use the
 W3C validator to validate your
 markup.
  |
 See
 Debugging HTML
 for a practical guide.
  |
| 4.1.2 Name, Role, Value (A) |
 The name and role of user interface components (e.g. form inputs,
 buttons, links, etc.) should be programmatically determinable.

 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.
  |
 See
 HTML: A good basis for accessibility
 and
 WAI-ARIA basics.
  |
| 4.1.3 Status Messages (AA) *added in 2.1* |
 Assistive technology users are made aware of new status messages added
 to the page.
  | Understanding Status Messages |

**Note:** Also see the WCAG description for Guideline 4.1: Compatible: Maximize compatibility with current and future user agents, including assistive technologies.

See also
--------

* WCAG
    1. Perceivable
    2. Operable
    3. Understandable
    4. Robust


Text labels and names - Accessibility

Text labels and names
=====================

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 `<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):

```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 for a live interactive example.

### See also

* `<area>`
* H24: Providing text alternatives for the area elements of image maps
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"` or `role="alertdialog"`; you can use the `aria-label` or `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"`
* `role="alertdialog"`
* `aria-label`
* `aria-labelledby`
* WAI-ARIA: dialog role
* Dialog authoring practices
Documents must have a title
---------------------------

It is important in each HTML document to include a `<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 `<title>` element is as follows:

```html
<title>
  <title>: 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

* `<title>`
Embedded content must be labeled
--------------------------------

Make sure that elements that embed content have a title attribute that describes the embedded content. This includes the `<embed>` and `<object>` elements. These elements are often used for graphical content, much like the `<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 `<figcaption>` within a `<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 `<img>` describes the appearance of the image; the `<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 `<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 `<fieldset>` element, you should include a nested `<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.

### See also

* `<fieldset>`
* `<legend>`
Form elements must be labeled
-----------------------------

All elements within a form must have a `<label>` that identifies its purpose. This applies to all types of `<input>` items, as well as `<button>`, `<output>`, `<select>`, `<textarea>`, `<progress>` and `<meter>` elements, as well as any element with the `switch` ARIA role.

The form element can be placed inside the `<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 `<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 `<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 `<iframe>` and the older, obsolete `<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 `<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 `<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 `<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 `<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 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 `<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 `<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 `<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, `<img>`, `<canvas>`, `<map>`, and `<area>` elements, as well as `<input>` elements where `type=image` and `<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 (`<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 `<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` attribute.

Use label attribute on optgroup elements
----------------------------------------

In an `<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 `<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` 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
Related WCAG success criteria
-----------------------------

1.1.1 Non-text Content (A)

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)

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)

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.


Color contrast - Accessibility

Color contrast
==============

The color contrast 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 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;
}
```

### 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;
}
```

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.

You can also check color contrast on the fly using Firefox's Developer Tools — see the Accessibility inspector guide, and in particular the section 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)

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)

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) (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
* Multiple labels
* Understanding Non-Text Contrast


Use of color - Accessibility

Use of color
============

While 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 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)

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
* Color contrast
* Color and color contrast in the Accessibility tutorials


CSS Counter Styles - Web APIs

CSS Counter Styles
==================

The CSS Counter Styles module allows to define custom counter styles, which can be used for CSS list-marker and generated-content counters.

Interfaces
----------

`CSSCounterStyleRule`

Represents an `@counter-style` rule.

Specifications
--------------

| Specification |
| --- |
| CSS Counter Styles Level 3 # the-csscounterstylerule-interface |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* CSS counter styles module
* Using CSS counters


Beacon API - Web APIs

Beacon API
==========

The **`Beacon`** API is used to send an asynchronous and non-blocking request to a web server. The request does not expect a response. Unlike requests made using `XMLHttpRequest` or the Fetch API, the browser guarantees to initiate beacon requests before the page is unloaded and to run them to completion.

The main use case for the Beacon API is to send analytics such as client-side events or session data to the server. Historically, websites have used `XMLHttpRequest` for this, but browsers do not guarantee to send these asynchronous requests in some circumstances (for example, if the page is about to be unloaded). To combat this, websites have resorted to various techniques, such as making the request synchronous, that have a bad effect on responsiveness. Because beacon requests are both asynchronous and guaranteed to be sent, they combine good performance characteristics and reliability.

For more details about the motivation for and usage of this API, see the documentation for the `navigator.sendBeacon()` method.

**Note:** This API is *not available* in Web Workers (not exposed via `WorkerNavigator`).

Interfaces
----------

This API defines a single method: `navigator.sendBeacon()`.

The method takes two arguments, the URL and the data to send in the request. The data argument is optional and its type may be a `TypedArray`, a `DataView`, a `Blob`, a string literal or object, or a `FormData` object. If the browser successfully queues the request for delivery, the method returns "`true`"; otherwise, it returns "`false`".

Specifications
--------------

| Specification |
| --- |
| Beacon # sendbeacon-method |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Beacon standard
* Beacon CanIUse data
* Intercepting beacons through service workers; Ehsan Akhgari; 2015-Apr-08
* https://webkit.org/blog/8821/link-click-analytics-and-privacy/
* Beaconing in Practice


FederatedCredential - Web APIs

FederatedCredential
===================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`FederatedCredential`** interface of the Credential Management API provides information about credentials from a federated identity provider. A federated identity provider is an entity that a website trusts to correctly authenticate a user, and that provides an API for that purpose. OpenID Connect is an example of a federated identity provider framework.

**Note:** The Federated Credential Management API (FedCM) provides a more complete solution for handling identity federation in the browser, and uses the `IdentityCredential` type.

In browsers that support it, an instance of this interface may be passed in the `credential` member of the `init` object for global `fetch()`.

Credential

FederatedCredentialConstructor
-----------

`FederatedCredential()`
Experimental

Creates a new `FederatedCredential` object.

Instance properties
-------------------

*Inherits properties from its ancestor, `Credential`.*

`FederatedCredential.provider` Read only
Experimental

Returns a string containing a credential's federated identity provider.

`FederatedCredential.protocol` Read only
Experimental

Returns a string containing a credential's federated identity protocol.

### Event handlers

None.

Instance methods
----------------

None.

Examples
--------

```js
const cred = new FederatedCredential({
  id,
  name,
  provider: "https://account.google.com",
  iconURL,
});

// Store it
navigator.credentials.store(cred).then(() => {
  // Do something else.
});
```

Specifications
--------------

| Specification |
| --- |
| Credential Management Level 1 # federated |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


XRSystem - Web APIs

XRSystem
========

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The WebXR Device API interface **`XRSystem`** provides methods which let you get access to an `XRSession` object representing a WebXR session. With that `XRSession` in hand, you can use it to interact with the Augmented Reality (AR) or Virtual Reality (VR) device.

EventTarget

XRSystemInstance properties
-------------------

*While `XRSystem` directly offers no properties, it does inherit properties from its parent interface, `EventTarget`.*

Instance methods
----------------

*In addition to inheriting methods from its parent interface, `EventTarget`, the `XRSystem` interface includes the following methods:*

`isSessionSupported()`
Experimental

 Returns a promise which resolves to `true` if the browser supports the given session mode.
 Resolves to `false` if the specified mode isn't supported.

`requestSession()`
Experimental

Returns a promise that resolves to a new `XRSession` with the specified session mode.

Events
------

`devicechange`
Experimental

 Sent when the set of available XR devices has changed.
 Also available using the `ondevicechange` event handler.

Usage notes
-----------

This interface was previously known as `XR` in earlier versions of the specification; if you see references to `XR` in code or documentation, replace that with `XRSystem`.

Examples
--------

The following example shows how to use both `isSessionSupported()` and `requestSession()`.

```js
if (navigator.xr) {
  immersiveButton.addEventListener("click", onButtonClicked);
  navigator.xr.isSessionSupported("immersive-vr").then((isSupported) => {
    immersiveButton.disabled = !isSupported;
  });
}

function onButtonClicked() {
  if (!xrSession) {
    navigator.xr.requestSession("immersive-vr").then((session) => {
      // onSessionStarted() not shown for reasons of brevity and clarity.
      onSessionStarted(session);
    });
  } else {
    // Shut down the already running XRSession
    xrSession.end().then(() => {
      // Since there are cases where the end event is not sent, call the handler here as well.
      onSessionEnded();
    });
  }
}
```

This code starts by checking to see if WebXR is available by looking for the `navigator.xr` property. If it's found, we know WebXR is present, so we proceed by establishing a handler for the button which the user can click to toggle immersive VR mode on and off.

However, we don't yet know if the desired immersive mode is available. To determine this, we call `isSessionSupported()`, passing it the desired session option before enabling the button, `immersiveButton`, which the user can then use to switch to immersive mode only if immersive VR mode is available. If immersive VR isn't available, the button is disabled to prevent its use.

The `onButtonClicked()` function checks to see if there's already a session running. If there isn't, we use `requestSession()` to start one and, once the returned promise resolves, we call a function `onSessionStarted()` to set up our session for rendering and so forth.

If, on the other hand, there is already an ongoing XR session, we instead call `end()` to end the current session. When the current session ends, the `end` event is sent, so set `xrSession` to `null` in its handler to record the fact that we no longer have an ongoing session. That way, if the user clicks the button again, a new session will start.

Specifications
--------------

| Specification |
| --- |
| WebXR Device API # xrsystem-interface |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


SVGVKernElement - Web APIs

SVGVKernElement
===============

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`SVGVKernElement`** interface corresponds to the `<vkern>` elements.

Object-oriented access to the attributes of the `<vkern>` element via the SVG DOM is not possible.

Instance properties
-------------------

*This interface has no properties but inherits properties from its parent, `SVGElement`.*

Instance methods
----------------

*This interface has no methods but inherits methods from its parent, `SVGElement`.*

Specifications
--------------

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 1.1 (Second Edition) # InterfaceSVGVKernElement |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `<vkern>`


HmacKeyGenParams - Web APIs

HmacKeyGenParams
================

The **`HmacKeyGenParams`** dictionary of the Web Crypto API represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.generateKey()`, when generating a key for the HMAC algorithm.

Instance properties
-------------------

`name`

A string. This should be set to `HMAC`.

`hash`

A string representing the name of the digest function to use. You can pass any of `SHA-1`, `SHA-256`, `SHA-384`, or `SHA-512` here.

`length` Optional

A `Number` — the length in bits of the key. If this is omitted, the length of the key is equal to the block size of the hash function you have chosen. Unless you have a good reason to use a different length, omit this property and use the default.

Examples
--------

See the examples for `SubtleCrypto.generateKey()`.

Specifications
--------------

| Specification |
| --- |
| Web Cryptography API # dfn-HmacKeyGenParams |

Browser compatibility
---------------------

Browsers that support the "HMAC" algorithm for the `SubtleCrypto.generateKey()` method will support this type.

See also
--------

* `SubtleCrypto.generateKey()`.


Text - Web APIs

Text
====

The **`Text`** interface represents a text `node` in a DOM tree.

EventTarget

Node

CharacterData

Text
To understand what a text node is, consider the following document:

```html
<html lang="en" class="e">
  <head>
    <title>Aliens?</title>
  </head>
  <body>
    Why yes.
  </body>
</html>
```

In that document, there are five text nodes, with the following contents:

* `"\n "` (after the `<head>` start tag, a newline followed by four spaces)
* `"Aliens?"` (the contents of the `title` element)
* `"\n "` (after the `</head>` end tag, a newline followed by two spaces)
* `"\n "` (after the `<body>` start tag, a newline followed by two spaces)
* `"\n Why yes.\n \n\n"` (the contents of the `body` element)

Each of those text nodes is an object that has the properties and methods documented in this article.

Constructor
-----------

`Text()`

Returns a new `Text` node with the parameter as its textual content.

Instance properties
-------------------

*Inherits properties from its parents, `CharacterData`, `Node`, and `EventTarget`.*

`Text.assignedSlot` Read only

Returns a `HTMLSlotElement` representing the `<slot>` the node is inserted in.

`Text.wholeText` Read only

Returns a string containing the text of all `Text` nodes logically adjacent to this `Node`, concatenated in document order.

Instance methods
----------------

*Inherits methods from its parent, `CharacterData`, `Node`, and `EventTarget`.*

`Text.splitText`

Breaks the node into two nodes at a specified offset.

Specifications
--------------

| Specification |
| --- |
| DOM Standard # interface-text |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The DOM API


GPUUncapturedErrorEvent - Web APIs

GPUUncapturedErrorEvent
=======================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`GPUUncapturedErrorEvent`** interface of the WebGPU API is the event object type for the `GPUDevice` `uncapturederror` event, used for telemetry and to report unexpected errors.

Known error cases should be handled using `pushErrorScope()` and `popErrorScope()`.

Event

GPUUncapturedErrorEventConstructor
-----------

`GPUUncapturedErrorEvent()`
Experimental

Creates a new `GPUUncapturedErrorEvent` object instance.

Instance properties
-------------------

*Inherits properties from its parent, `Event`.*

`error`
Experimental
 Read only

A `GPUError` object instance providing access to the details of the error.

Examples
--------

You could use something like the following as a global mechanism to pick up any errors that aren't handled by error scopes and capture them.

```js
// ...

device.addEventListener("uncapturederror", (event) => {
  // Re-surface the error
  console.error("A WebGPU error was not captured:", event.error.message);
  reportErrorToServer({
    type: event.error.constructor.name,
    message: event.error.message,
  });
});

// ...
```

Specifications
--------------

| Specification |
| --- |
| WebGPU # gpuuncapturederrorevent |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The WebGPU API
* WebGPU Error Handling best practices


SVGLinearGradientElement - Web APIs

SVGLinearGradientElement
========================

The **`SVGLinearGradientElement`** interface corresponds to the `<linearGradient>` element.

EventTarget

Node

Element

SVGElement

SVGGradientElement

SVGLinearGradientElementInstance properties
-------------------

*This interface also inherits properties from its parent, `SVGGradientElement`.*

`SVGLinearGradientElement.x1` Read only

An `SVGAnimatedLength` corresponding to the `x1` attribute of the given `<linearGradient>` element.

`SVGLinearGradientElement.y1` Read only

An `SVGAnimatedLength` corresponding to the `y1` attribute of the given `<linearGradient>` element.

`SVGLinearGradientElement.x2` Read only

An `SVGAnimatedLength` corresponding to the `x2` attribute of the given `<linearGradient>` element.

`SVGLinearGradientElement.y2` Read only

An `SVGAnimatedLength` corresponding to the `y2` attribute of the given `<linearGradient>` element.

Instance methods
----------------

*This interface doesn't implement any specific methods, but inherits methods from its parent interface, `SVGGradientElement`.*

Specifications
--------------

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 2 # InterfaceSVGLinearGradientElement |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


MediaRecorder - Web APIs

MediaRecorder
=============

The **`MediaRecorder`** interface of the MediaStream Recording API provides functionality to easily record media. It is created using the `MediaRecorder()` constructor.

EventTarget

MediaRecorderConstructor
-----------

`MediaRecorder()`

Creates a new `MediaRecorder` object, given a `MediaStream` to record. Options are available to do things like set the container's MIME type (such as `"video/webm"` or `"video/mp4"`) and the bit rates of the audio and video tracks or a single overall bit rate.

Instance properties
-------------------

`MediaRecorder.mimeType` Read only

Returns the MIME type that was selected as the recording container for the `MediaRecorder` object when it was created.

`MediaRecorder.state` Read only

Returns the current state of the `MediaRecorder` object (`inactive`, `recording`, or `paused`.)

`MediaRecorder.stream` Read only

Returns the stream that was passed into the constructor when the `MediaRecorder` was created.

`MediaRecorder.videoBitsPerSecond` Read only

Returns the video encoding bit rate in use. This may differ from the bit rate specified in the constructor (if it was provided).

`MediaRecorder.audioBitsPerSecond` Read only

Returns the audio encoding bit rate in use. This may differ from the bit rate specified in the constructor (if it was provided).

`MediaRecorder.audioBitrateMode` Read only
Experimental

Returns the bitrate mode used to encode audio tracks.

Static methods
--------------

`MediaRecorder.isTypeSupported()`

A static method which returns a `true` or `false` value indicating if the given MIME media type is supported by the current user agent.

Instance methods
----------------

`MediaRecorder.pause()`

Pauses the recording of media.

`MediaRecorder.requestData()`

Requests a `Blob` containing the saved data received thus far (or since the last time `requestData()` was called. After calling this method, recording continues, but in a new `Blob`.

`MediaRecorder.resume()`

Resumes recording of media after having been paused.

`MediaRecorder.start()`

Begins recording media; this method can optionally be passed a `timeslice` argument with a value in milliseconds. If this is specified, the media will be captured in separate chunks of that duration, rather than the default behavior of recording the media in a single large chunk.

`MediaRecorder.stop()`

Stops recording, at which point a `dataavailable` event containing the final `Blob` of saved data is fired. No more recording occurs.

Events
------

Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface.

`dataavailable`

Fires periodically each time `timeslice` milliseconds of media have been recorded (or when the entire media has been recorded, if `timeslice` wasn't specified). The event, of type `BlobEvent`, contains the recorded media in its `data` property.

`error`

Fired when there are fatal errors that stop recording. The received event is based on the `MediaRecorderErrorEvent` interface, whose `error` property contains a `DOMException` that describes the actual error that occurred.

`pause`

Fired when media recording is paused.

`resume`

Fired when media recording resumes after being paused.

`start`

Fired when media recording starts.

`stop`

Fired when media recording ends, either when the `MediaStream` ends, or after the `MediaRecorder.stop()` method is called.

Example
-------

```js
if (navigator.mediaDevices) {
  console.log("getUserMedia supported.");

  const constraints = { audio: true };
  let chunks = [];

  navigator.mediaDevices
    .getUserMedia(constraints)
    .then((stream) => {
      const mediaRecorder = new MediaRecorder(stream);

      record.onclick = () => {
        mediaRecorder.start();
        console.log(mediaRecorder.state);
        console.log("recorder started");
        record.style.background = "red";
        record.style.color = "black";
      };

      stop.onclick = () => {
        mediaRecorder.stop();
        console.log(mediaRecorder.state);
        console.log("recorder stopped");
        record.style.background = "";
        record.style.color = "";
      };

      mediaRecorder.onstop = (e) => {
        console.log("data available after MediaRecorder.stop() called.");

        const clipName = prompt("Enter a name for your sound clip");

        const clipContainer = document.createElement("article");
        const clipLabel = document.createElement("p");
        const audio = document.createElement("audio");
        const deleteButton = document.createElement("button");
        const mainContainer = document.querySelector("body");

        clipContainer.classList.add("clip");
        audio.setAttribute("controls", "");
        deleteButton.textContent = "Delete";
        clipLabel.textContent = clipName;

        clipContainer.appendChild(audio);
        clipContainer.appendChild(clipLabel);
        clipContainer.appendChild(deleteButton);
        mainContainer.appendChild(clipContainer);

        audio.controls = true;
        const blob = new Blob(chunks, { type: "audio/ogg; codecs=opus" });
        chunks = [];
        const audioURL = URL.createObjectURL(blob);
        audio.src = audioURL;
        console.log("recorder stopped");

        deleteButton.onclick = (e) => {
          const evtTgt = e.target;
          evtTgt.parentNode.parentNode.removeChild(evtTgt.parentNode);
        };
      };

      mediaRecorder.ondataavailable = (e) => {
        chunks.push(e.data);
      };
    })
    .catch((err) => {
      console.error(`The following error occurred: ${err}`);
    });
}
```

**Note:** This code sample is inspired by the Web Dictaphone demo. Some lines have been omitted for brevity; refer to the source for the complete code.

Specifications
--------------

| Specification |
| --- |
| MediaStream Recording # mediarecorder-api |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the MediaStream Recording API
* Web Dictaphone: MediaRecorder + getUserMedia + Web Audio API visualization demo, by Chris Mills (source on GitHub.)
* Recording a media element
* simpl.info MediaStream Recording demo, by Sam Dutton.
* `MediaDevices.getUserMedia()`
* OpenLang: HTML video language lab web application using MediaDevices and the MediaStream Recording API for video recording (source on GitHub)


MediaStream Image Capture API - Web APIs

MediaStream Image Capture API
=============================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **MediaStream Image Capture API** is an API for capturing images or videos from a photographic device. In addition to capturing data, it also allows you to retrieve information about device capabilities such as image size, red-eye reduction and whether or not there is a flash and what they are currently set to. Conversely, the API allows the capabilities to be configured within the constraints what the device allows.

MediaStream image capture concepts and usage
--------------------------------------------

The process of retrieving an image or video stream happens as described below. The example code is adapted from Chrome's Image Capture examples.

First, get a reference to a device by calling `MediaDevices.getUserMedia()`. The example below says give me whatever video device is available, though the `getUserMedia()` method allows more specific capabilities to be requested. This method returns a `Promise` that resolves with a `MediaStream` object.

```js
navigator.mediaDevices.getUserMedia({ video: true }).then((mediaStream) => {
  // Do something with the stream.
});
```

Next, isolate the visual part of the media stream. Do this by calling `MediaStream.getVideoTracks()`. This returns an array of `MediaStreamTrack` objects. The code below assumes that the first item in the `MediaStreamTrack` array is the one to use. You can use the properties of the `MediaStreamTrack` objects to select the one you need.

```js
const track = mediaStream.getVideoTracks()[0];
```

At this point, you might want to configure the device capabilities before capturing an image. You can do this by calling `applyConstraints()` on the track object before doing anything else.

```js
let zoom = document.querySelector("#zoom");
const capabilities = track.getCapabilities();
// Check whether zoom is supported or not.
if (!capabilities.zoom) {
  return;
}
track.applyConstraints({ advanced: [{ zoom: zoom.value }] });
```

Finally, pass the `MediaStreamTrack` object to the `ImageCapture()` constructor. Though a `MediaStream` holds several types of tracks and provides multiple methods for retrieving them, the ImageCapture constructor will throw a `DOMException` of type `NotSupportedError` if `MediaStreamTrack.kind` is not `"video"`.

```js
let imageCapture = new ImageCapture(track);
```

Interfaces
----------

`ImageCapture`
Experimental

An interface for capturing images from a photographic device referenced through a valid `MediaStreamTrack`.

Specifications
--------------

| Specification |
| --- |
| MediaStream Image Capture # imagecaptureapi |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `MediaStream`
* `MediaStreamTrack`


TreeWalker - Web APIs

TreeWalker
==========

The **`TreeWalker`** object represents the nodes of a document subtree and a position within them.

A `TreeWalker` can be created using the `Document.createTreeWalker()` method.

Instance properties
-------------------

*This interface doesn't inherit any property.*

`TreeWalker.root` Read only

Returns a `Node` representing the root node as specified when the `TreeWalker` was created.

`TreeWalker.whatToShow` Read only

Returns an `unsigned long` being a bitmask made of constants describing the types of `Node` that must be presented. Non-matching nodes are skipped, but their children may be included, if relevant. The possible values are:

| Constant | Numerical value | Description |
| --- | --- | --- |
| `NodeFilter.SHOW_ALL` | `4294967295` (that is the max value of `unsigned long`) | Shows all nodes. |
| `NodeFilter.SHOW_ATTRIBUTE`
Deprecated
 | `2` | Shows attribute `Attr` nodes. This is meaningful only when creating a `TreeWalker` with an `Attr` node as its root. In this case, it means that the attribute node will appear in the first position of the iteration or traversal. Since attributes are never children of other nodes, they do not appear when traversing over the document tree. |
| `NodeFilter.SHOW_CDATA_SECTION`
Deprecated
 | `8` | Shows `CDATASection` nodes. |
| `NodeFilter.SHOW_COMMENT` | `128` | Shows `Comment` nodes. |
| `NodeFilter.SHOW_DOCUMENT` | `256` | Shows `Document` nodes. |
| `NodeFilter.SHOW_DOCUMENT_FRAGMENT` | `1024` | Shows `DocumentFragment` nodes. |
| `NodeFilter.SHOW_DOCUMENT_TYPE` | `512` | Shows `DocumentType` nodes. |
| `NodeFilter.SHOW_ELEMENT` | `1` | Shows `Element` nodes. |
| `NodeFilter.SHOW_ENTITY`
Deprecated
 | `32` | Legacy, no more usable. |
| `NodeFilter.SHOW_ENTITY_REFERENCE`
Deprecated
 | `16` | Legacy, no more usable. |
| `NodeFilter.SHOW_NOTATION`
Deprecated
 | `2048` | Legacy, no more usable. |
| `NodeFilter.SHOW_PROCESSING_INSTRUCTION` | `64` | Shows `ProcessingInstruction` nodes. |
| `NodeFilter.SHOW_TEXT` | `4` | Shows `Text` nodes. |

`TreeWalker.filter` Read only

Returns a `NodeFilter` used to select the relevant nodes.

`TreeWalker.currentNode`

Is the `Node` on which the `TreeWalker` is currently pointing at.

Instance methods
----------------

*This interface doesn't inherit any method.*

**Note:** in the context of a `TreeWalker`, a node is *visible* if it exists in the logical view determined by the `whatToShow` and `filter` parameter arguments. (Whether or not the node is visible on the screen is irrelevant.)

`TreeWalker.parentNode()`

Moves the current `Node` to the first *visible* ancestor node in the document order, and returns the found node. It also moves the current node to this one. If no such node exists, or if it is before that the *root node* defined at the object construction, returns `null` and the current node is not changed.

`TreeWalker.firstChild()`

Moves the current `Node` to the first *visible* child of the current node, and returns the found child. It also moves the current node to this child. If no such child exists, returns `null` and the current node is not changed. Note that the node returned by `firstChild()` is dependent on the value of `whatToShow` set during instantiation of the `TreeWalker` object. Assuming the following HTML tree, and if you set the `whatToShow` to `NodeFilter.SHOW_ALL` a call to `firstChild()` will return a `Text` node and not an `HTMLDivElement` object.

```html
<!DOCTYPE html>
<html lang="en">
  <head><title>Demo</title>
  <body>
    <div id="container"></div>
  </body>
</html>
```

```js
let walker = document.createTreeWalker(document.body, NodeFilter.SHOW\_ALL);
let node = walker.firstChild(); // nodeName: "#text"
```

But if we do:

```js
let walker = document.createTreeWalker(
  document.body,
  NodeFilter.SHOW\_ELEMENT,
);
let node = walker.firstChild(); // nodeName: "DIV"
```

The same applies to `nextSibling()`, `previousSibling()`, `firstChild()` and `lastChild()`

`TreeWalker.lastChild()`

Moves the current `Node` to the last *visible* child of the current node, and returns the found child. It also moves the current node to this child. If no such child exists, `null` is returned and the current node is not changed.

`TreeWalker.previousSibling()`

Moves the current `Node` to its previous sibling, if any, and returns the found sibling. If there is no such node, return `null` and the current node is not changed.

`TreeWalker.nextSibling()`

Moves the current `Node` to its next sibling, if any, and returns the found sibling. If there is no such node, `null` is returned and the current node is not changed.

`TreeWalker.previousNode()`

Moves the current `Node` to the previous *visible* node in the document order, and returns the found node. It also moves the current node to this one. If no such node exists, or if it is before that the *root node* defined at the object construction, returns `null` and the current node is not changed.

`TreeWalker.nextNode()`

Moves the current `Node` to the next *visible* node in the document order, and returns the found node. It also moves the current node to this one. If no such node exists, returns `null` and the current node is not changed.

Specifications
--------------

| Specification |
| --- |
| DOM Standard # interface-treewalker |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The creator method: `Document.createTreeWalker()`.
* Related interface: `NodeIterator`.


TextEncoder - Web APIs

TextEncoder
===========

The **`TextEncoder`** interface takes a stream of code points as input and emits a stream of UTF-8 bytes.

**Note:** This feature is available in Web Workers

Constructor
-----------

`TextEncoder()`

Returns a newly constructed `TextEncoder` that will generate a byte stream with UTF-8 encoding.

Instance properties
-------------------

*The `TextEncoder` interface doesn't inherit any properties.*

`TextEncoder.encoding` Read only

Always returns `utf-8`.

Instance methods
----------------

*The `TextEncoder` interface doesn't inherit any methods*.

`TextEncoder.encode()`

Takes a string as input, and returns a `Uint8Array` containing UTF-8 encoded text.

`TextEncoder.encodeInto()`

 Takes a string to encode and a destination `Uint8Array` to put resulting UTF-8 encoded text into, and returns an object indicating the progress of the encoding.
 This is potentially more performant than the older `encode()` method.

Examples
--------

```js
const encoder = new TextEncoder();
const view = encoder.encode("€");
console.log(view); // Uint8Array(3) [226, 130, 172]
```

Specifications
--------------

| Specification |
| --- |
| Encoding Standard # interface-textencoder |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `TextDecoder` interface describing the inverse operation.
* Node.js supports global export from v11.0.0


HTMLHtmlElement - Web APIs

HTMLHtmlElement
===============

The **`HTMLHtmlElement`** interface serves as the root node for a given HTML document. This object inherits the properties and methods described in the `HTMLElement` interface.

You can retrieve the `HTMLHtmlElement` object for a given document by reading the value of the `document.documentElement` property.

EventTarget

Node

Element

HTMLElement

HTMLHtmlElementInstance properties
-------------------

*Inherits properties from its parent, `HTMLElement`.*

`HTMLHtmlElement.version`
Deprecated

A string representing the version of the HTML Document Type Definition (DTD) that governs this document. This property should not be used any more as it is non-conforming. Omit it.

Instance methods
----------------

*No specific method; inherits methods from its parent, `HTMLElement`.*

Specifications
--------------

| Specification |
| --- |
| HTML Standard # htmlhtmlelement |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* HTML element implementing this interface: `<html>`.


Channel Messaging API - Web APIs

Channel Messaging API
=====================

The **Channel Messaging API** allows two separate scripts running in different browsing contexts attached to the same document (e.g., two IFrames, or the main document and an IFrame, two documents via a `SharedWorker`, or two workers) to communicate directly, passing messages between one another through two-way channels (or pipes) with a port at each end.

**Note:** This feature is available in Web Workers

Concepts and usage
------------------

A message channel is created using the `MessageChannel()` constructor. Once created, the two ports of the channel can be accessed through the `MessageChannel.port1` and `MessageChannel.port2` properties (which both return `MessagePort` objects.) The app that created the channel uses `port1`, and the app at the other end of the port uses `port2` — you send a message to `port2`, and transfer the port over to the other browsing context using `window.postMessage` along with two arguments (the message to send, and the object to transfer ownership of, in this case the port itself.)

When these transferable objects are transferred, they are no longer usable on the context they previously belonged to. A port, after it is sent, can no longer be used by the original context.

The other browsing context can listen for the message using `onmessage`, and grab the contents of the message using the event's `data` attribute. You could then respond by sending a message back to the original document using `MessagePort.postMessage`.

When you want to stop sending messages down the channel, you can invoke `MessagePort.close` to close the ports.

Find out more about how to use this API in Using channel messaging.

Interfaces
----------

`MessageChannel`

Creates a new message channel to send messages across.

`MessagePort`

Controls the ports on the message channel, allowing sending of messages from one port and listening out for them arriving at the other.

Examples
--------

* We have published a channel messaging basic demo on GitHub (run it live too), which shows a really simple single message transfer between a page and an embedded `<iframe>`.
* You can also see a multimessaging demo (run this live), which shows a slightly more complex setup that can send multiple messages between main page and IFrame.
Specifications
--------------

| Specification |
| --- |
| HTML Standard # channel-messaging |

Browser compatibility
---------------------

### api.MessageChannel

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### api.MessagePort

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using channel messaging
* Web Workers API
* Broadcast Channel API


EcKeyGenParams - Web APIs

EcKeyGenParams
==============

The **`EcKeyGenParams`** dictionary of the Web Crypto API represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.generateKey()`, when generating any elliptic-curve-based key pair: that is, when the algorithm is identified as either of ECDSA or ECDH.

Instance properties
-------------------

`name`

A string. This should be set to `ECDSA` or `ECDH`, depending on the algorithm you want to use.

`namedCurve`

A string representing the name of the elliptic curve to use. This may be any of the following names for NIST-approved curves:

* `P-256`
* `P-384`
* `P-521`

Examples
--------

See the examples for `SubtleCrypto.generateKey()`.

Specifications
--------------

| Specification |
| --- |
| Web Cryptography API # dfn-EcKeyGenParams |

Browser compatibility
---------------------

Browsers that support the "ECDH" or "ECDSA" algorithms for the `SubtleCrypto.generateKey()` method will support this type.

See also
--------

* `SubtleCrypto.generateKey()`.


DOMQuad - Web APIs

DOMQuad
=======

A `DOMQuad` is a collection of four `DOMPoint`s defining the corners of an arbitrary quadrilateral. Returning `DOMQuad`s lets `getBoxQuads()` return accurate information even when arbitrary 2D or 3D transforms are present. It has a handy `bounds` attribute returning a `DOMRectReadOnly` for those cases where you just want an axis-aligned bounding rectangle.

Constructor
-----------

`DOMQuad()`

Creates a new `DOMQuad` object.

Instance properties
-------------------

p1,p2,p3,p4 Read only

are `DOMPoint` objects for each of the `DOMQuad` object's four corners.

Instance methods
----------------

`DOMQuad.fromRect()`

Returns a new `DOMQuad` object based on the passed set of coordinates.

`DOMQuad.fromQuad()`

Returns a new `DOMQuad` object based on the passed set of coordinates.

`DOMQuad.getBounds()`

Returns a `DOMRect` object with the coordinates and dimensions of the `DOMQuad` object.

`DOMQuad.toJSON()`

Returns a JSON representation of the `DOMQuad` object.

Specifications
--------------

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # DOMQuad |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.