### Programmatic Menu Opening
Source: https://inclusive-components.design/menus-menu-buttons
Example of initializing and opening a menu button programmatically.
```javascript
exampleMenuButton = new MenuButton(document.querySelector('[aria-haspopup]'));
exampleMenuButton.open();
```
--------------------------------
### Install component via NPM
Source: https://inclusive-components.design/a-theme-switcher
Use the NPM command to add the theme switcher package to your project.
```bash
npm i --save react-theme-switch
```
--------------------------------
### Demo markup for toggle sections
Source: https://inclusive-components.design/collapsible-sections
Example structure for toggle-section components with unique IDs for hash tracking.
```html
Section 1
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam non lectus sit amet nunc facilisis molestie. Praesent quis libero et mauris facilisis dignissim at sed nisi.
Nullam efficitur porttitor lectus, ac finibus nibh fermentum ac. Phasellus aliquam, nibh non efficitur pharetra, tellus diam posuere lectus, a consequat elit ex nec ligula.
Section 2
Aliquam erat volutpat. Nulla facilisi. Nunc porttitor, elit non eleifend aliquam, est leo scelerisque nibh, nec faucibus odio urna ac nulla.
Maecenas laoreet in metus eget convallis. Vivamus at eleifend felis. Proin non vehicula neque. Etiam eleifend sapien ut nulla malesuada, ac condimentum nisl efficitur.
```
--------------------------------
### Install inclusive-menu-button via NPM
Source: https://inclusive-components.design/menus-menu-buttons
Use this command to add the inclusive-menu-button package to your project dependencies.
```bash
npm i inclusive-menu-button --save
```
--------------------------------
### HTML structure for toggle sections
Source: https://inclusive-components.design/collapsible-sections
Markup example using the custom toggle-section element.
```html
Section 1
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam non lectus sit amet nunc facilisis molestie. Praesent quis libero et mauris facilisis dignissim at sed nisi.
Nullam efficitur porttitor lectus, ac finibus nibh fermentum ac. Phasellus aliquam, nibh non efficitur pharetra, tellus diam posuere lectus, a consequat elit ex nec ligula.
Section 2
Aliquam erat volutpat. Nulla facilisi. Nunc porttitor, elit non eleifend aliquam, est leo scelerisque nibh, nec faucibus odio urna ac nulla.
Maecenas laoreet in metus eget convallis. Vivamus at eleifend felis. Proin non vehicula neque. Etiam eleifend sapien ut nulla malesuada, ac condimentum nisl efficitur.
```
--------------------------------
### Implement responsive table component in React
Source: https://inclusive-components.design/data-tables
A full component example demonstrating dynamic tabindex management based on scrollability.
```javascript
class Table extends React.Component {
constructor(props) {
super(props)
this.state = {
tabindex: null
}
}
componentDidMount() {
let container = ReactDOM.findDOMNode(this.refs.container);
let scrollable = container.scrollWidth > container.clientWidth;
this.setState({
tabindex: scrollable ? '0' : null
});
}
render() {
const captionID = 'caption-' + Math.random().toString(36).substr(2, 9);
return (
);
}
}
```
--------------------------------
### Render ThemeSwitch markup
Source: https://inclusive-components.design/a-theme-switcher
Example JSX structure for the theme toggle button and embedded stylesheet.
```jsx
dark theme:
off
```
--------------------------------
### SVG Use Element Implementation
Source: https://inclusive-components.design/collapsible-sections
Example of using the SVG element for icon reuse, noting the limitation regarding CSS targeting.
```xml
My section
```
--------------------------------
### Web component definition
Source: https://inclusive-components.design/collapsible-sections
JavaScript implementation of the custom element including template and Shadow DOM setup.
```javascript
(function() {
// Check for support
if ('content' in document.createElement('template')) {
const tmpl = document.createElement('template')
// Create the web component's template
// featuring a for the Light DOM content
tmpl.innerHTML = `
`
// Check for latest Shadow DOM syntax support
if (document.head.attachShadow) {
class ToggleSection extends HTMLElement {
constructor() {
super()
// Make the host element a region
this.setAttribute('role', 'region')
// Create a `shadowRoot` and populate from template
this.attachShadow({ mode: 'open' })
this.shadowRoot.appendChild(tmpl.content.cloneNode(true))
// Assign the toggle button
this.btn = this.shadowRoot.querySelector('h2 button')
// Get the first element in Light DOM
// and cast its heading level (which should, but may not, exist)
const oldHeading = this.querySelector(':first-child')
let level = parseInt(oldHeading.tagName.substr(1))
```
--------------------------------
### Define the Shadow DOM heading structure
Source: https://inclusive-components.design/collapsible-sections
Example HTML structure for the collapsible heading containing a button and icon.
```html
```
--------------------------------
### Non-Interactive Element Focusability
Source: https://inclusive-components.design/tabbed-interfaces
Examples demonstrating the difference between making an element focusable via tab order versus script-only focus.
```html
Section 3
```
```html
Application View
```
--------------------------------
### Invalid focusable element example
Source: https://inclusive-components.design/rss
An example of an element that violates WCAG 2.4.3 by making a non-interactive element focusable via tabindex.
```html
Section 3
```
--------------------------------
### Initialize React project
Source: https://inclusive-components.design/a-theme-switcher
Commands to set up a new React development environment.
```bash
npm i -g create-react-app
create-react-app theme-switch
cd theme-switch
npm start
```
--------------------------------
### Empty Navigation Region
Source: https://inclusive-components.design/menus-menu-buttons
Example of an empty navigation region when the list is hidden from screen readers.
```html
```
--------------------------------
### Import ThemeSwitch component
Source: https://inclusive-components.design/a-theme-switcher
Import the component into the App.js file.
```javascript
import ThemeSwitch from './components/ThemeSwitch'
```
--------------------------------
### Apply menu and menuitem roles to a list
Source: https://inclusive-components.design/menus-menu-buttons
Demonstrates how to augment a standard list with WAI-ARIA menu semantics.
```html
```
--------------------------------
### Style instructions for touch devices
Source: https://inclusive-components.design/rss
Use the .touch class to override default instruction visibility when touch interaction is detected.
```css
.touch .instructions p { display: none !important; } .touch .instructions #touch { display: block !important; }
```
--------------------------------
### Empty Navigation Region
Source: https://inclusive-components.design/rss
An example of an empty navigation region, which can occur if the button is placed outside the nav element.
```html
```
--------------------------------
### Initialize localStorage alias
Source: https://inclusive-components.design/a-theme-switcher
Create a safe reference to localStorage to avoid linting errors.
```javascript
this.store = typeof localStorage === 'undefined' ? null : localStorage;
```
--------------------------------
### Full CSS styling for target-based navigation
Source: https://inclusive-components.design/tabbed-interfaces
Complete stylesheet including typography, layout, and the :target visibility logic.
```css
@import url('https://fonts.googleapis.com/css?family=Asap:400,400i,700');
html {
font-size: 125%;
font-family: Asap, sans-serif;
}
body {
max-width: 40rem;
padding: 0 1rem;
margin: 1.5rem auto;
}
* {
color: inherit;
}
[aria-labelledby="toc-heading"] {
padding: 1rem;
border: 2px solid;
}
[aria-labelledby="toc-heading"] * {
margin: 0;
}
section:not(:target) {
display: none;
}
```
--------------------------------
### Menu Button Open Method
Source: https://inclusive-components.design/menus-menu-buttons
Implementation of the open method to update aria-expanded, reveal the menu, and focus the first enabled item.
```javascript
MenuButton.prototype.open = function () {
this.button.setAttribute('aria-expanded', true);
this.menu.hidden = false;
this.menu.querySelector(':not([disabled])').focus();
return this;
}
```
--------------------------------
### Card with Nested Links
Source: https://inclusive-components.design/rss
An example of adding an interactive author link inside a block-level card link, which can cause accessibility issues.
```html
Card design woes
Ten common pitfalls to avoid when designing card components.
By Heydon Pickering
```
--------------------------------
### Basic Menu Button Structure
Source: https://inclusive-components.design/menus-menu-buttons
A standard menu button implementation using a button trigger and a container with the menu role.
```html
Difficulty
▾
Easy
Medium
Incredibly Hard
```
--------------------------------
### Instantiate an on-demand live region
Source: https://inclusive-components.design/rss
Use the OnDemandLiveRegion module to programmatically trigger screen reader announcements for events in your scripts.
```javascript
const liveRegion = new OnDemandLiveRegion()
liveRegion.say('Take a short break!')
```
--------------------------------
### Non-Accessible Data Table
Source: https://inclusive-components.design/data-tables
An example of a table that lacks semantic header elements, making it difficult for screen readers to interpret the data structure.
```html
Column header 1
Column header 2
Row one, first cell
Row one, second cell
```
--------------------------------
### Initialize Toggletip Functionality
Source: https://inclusive-components.design/tooltips-toggletips
JavaScript to dynamically create the toggletip button and handle interaction events.
```javascript
(function() {
// Get all the toggletip buttons
var toggletipTexts = document.querySelectorAll('[data-toggletip]');
// Iterate over them
Array.prototype.forEach.call(toggletipTexts, function(toggletipText) {
// Create the container element
var container = document.createElement('span');
container.setAttribute('class', 'toggletip-container');
// Put it before the original element in the DOM
toggletipText.parentNode.insertBefore(container, toggletipText);
// Create the button element
var toggletip = document.createElement('button');
toggletip.setAttribute('type', 'button');
toggletip.setAttribute('aria-label', 'more info');
toggletip.setAttribute('data-toggletip-content', toggletipText.textContent);
toggletip.textContent = 'i';
// Place the button element in the container
container.appendChild(toggletip);
// Create the live region
var liveRegion = document.createElement('span');
liveRegion.setAttribute('role', 'status');
// Place the live region in the container
container.appendChild(liveRegion);
// Remove the original element
toggletipText.parentNode.removeChild(toggletipText);
// Build `data-tooltip-content`
var message = toggletip.getAttribute('data-toggletip-content');
toggletip.setAttribute('data-toggletip-content', message);
toggletip.removeAttribute('title');
// Get the message from the data-content element
var message = toggletip.getAttribute('data-toggletip-content');
// Get the live region element
var liveRegion = toggletip.nextElementSibling;
// Toggle the message
toggletip.addEventListener('click', function() {
liveRegion.innerHTML = '';
window.setTimeout(function() {
liveRegion.innerHTML = ''+ message +' ';
}, 100);
});
// Close on outside click
document.addEventListener('click', function (e) {
if (toggletip !== e.target) {
liveRegion.innerHTML = '';
}
});
// Remove toggletip on ESC
toggletip.addEventListener('keydown', function(e) {
if ((e.keyCode || e.which) === 27)
liveRegion.innerHTML = '';
});
// Remove on blur
toggletip.addEventListener('blur', function (e) {
liveRegion.innerHTML = '';
});
});
}());
```
--------------------------------
### Define a reusable SVG symbol
Source: https://inclusive-components.design/rss
Define icons as symbols at the start of the document to reduce DOM bloat when using multiple instances of the same icon.
```html
```
--------------------------------
### Procedural Live Region Module
Source: https://inclusive-components.design/notifications
Instantiate and use a live region module to programmatically announce messages to screen readers.
```javascript
const liveRegion = new OnDemandLiveRegion()
liveRegion.say('Take a short break!')
```
--------------------------------
### Redundant title attribute example
Source: https://inclusive-components.design/tooltips-toggletips
Demonstrates an anti-pattern where the title attribute repeats the visible text node, causing unnecessary repetition for screen readers.
```html
Heydon's special page
```
--------------------------------
### Define Live Region
Source: https://inclusive-components.design/rss
Create a container for dynamic content updates that screen readers will announce automatically.
```html
```
--------------------------------
### Standard Navigation Structure
Source: https://inclusive-components.design/menus-menu-buttons
A standard navigation list structure without JavaScript enhancement.
```html
```
--------------------------------
### Feature detection for Web Components
Source: https://inclusive-components.design/collapsible-sections
Check for template and Shadow DOM support before initializing the component.
```javascript
if ('content' in document.createElement('template')) {
// Define the for the web component
if (document.head.attachShadow) {
// Define the web component using the v1 syntax
}
}
```
--------------------------------
### Define toggle and status helper functions
Source: https://inclusive-components.design/a-theme-switcher
Implement helper methods to check and update the theme state.
```javascript
isActive = () => this.state.active;
toggle = () => {
this.setState({
active: !this.isActive()
});
}
```
--------------------------------
### Initial Navigation Link Structure
Source: https://inclusive-components.design/menus-menu-buttons
A basic navigation structure using a link to jump to the navigation section.
```html
navigation
```
--------------------------------
### Basic Live Region Implementation
Source: https://inclusive-components.design/notifications
Use both role="status" and aria-live="polite" to maximize compatibility across different browser and assistive technology combinations.
```html
```
```html
Take a short break!
```
--------------------------------
### Style touch-specific instructions
Source: https://inclusive-components.design/a-content-slider
CSS rules to hide keyboard instructions and display touch-specific messages when the touch class is present.
```css
.touch .instructions p {
display: none !important;
}
.touch .instructions #touch {
display: block !important;
}
```
--------------------------------
### Detect touch interaction with JavaScript
Source: https://inclusive-components.design/rss
Listen for a single touchstart event to add a class to the body, then remove the listener to avoid redundant execution.
```javascript
window.addEventListener('touchstart', function touched() { document.body.classList.add('touch') window.removeEventListener('touchstart', touched, false) }, false)
```
--------------------------------
### Integrate ThemeSwitch into App.js
Source: https://inclusive-components.design/a-theme-switcher
Add the ThemeSwitch component to the main application render function.
```javascript
class App extends Component {
render() {
return (
Welcome to React
To get started, edit {gfm-js-extract-pre-1} and save to reload.
);
}
}
```
--------------------------------
### Toggle responsive display via CSS
Source: https://inclusive-components.design/rss
Uses media queries to switch between table and list layouts based on viewport width.
```css
@media (min-width: 400px) { .table-container { display: block; } .lists-container { display: none; } }
```
--------------------------------
### Listen for the choose event
Source: https://inclusive-components.design/menus-menu-buttons
Attaches an event listener to update the live region content when a menu item is selected.
```javascript
exampleMenuButton.addEventListener('choose', function (e) {
// Get the node's text content (label)
var choiceLabel = e.details.choice.textContent;
// Get the live region node
var liveRegion = document.getElementById('menuFeedback');
// Populate the live region
liveRegion.textContent = `Your difficulty level is ${choiceLabel}`;
}):
```
--------------------------------
### Implement Progressive Enhancement Navigation Link
Source: https://inclusive-components.design/rss
Provides a fallback navigation link for environments without JavaScript, pointing to a navigation block further down the document.
```html
navigation
```
--------------------------------
### Initialize component state
Source: https://inclusive-components.design/a-theme-switcher
Set the initial active state for the theme switcher in the constructor.
```javascript
constructor(props) {
super(props);
this.state = {
active: 'false'
};
}
```
--------------------------------
### Implement CSS-based Tooltips
Source: https://inclusive-components.design/rss
Use CSS to show tooltips on hover and focus states for elements with the tooltip role.
```css
[role="tooltip"] { display: none; } button:hover + [role="tooltip"], button:focus + [role="tooltip"] { display: block; }
```
--------------------------------
### Associate slider with instructions using aria-describedby
Source: https://inclusive-components.design/rss
Use aria-describedby to link a region to an element containing descriptive text for screen readers.
```html
scroll for more
use your arrow keys for more
```
--------------------------------
### Implement Algorithmic Margin Management
Source: https://inclusive-components.design/cards
Comprehensive CSS for managing spacing and alignment within the card component.
```css
.card, .card .text {
display: flex;
flex-direction: column;
}
.card .text {
flex-grow: 1;
}
.card .text > * + * {
margin-top: 0.75rem;
}
.card .text :last-child {
margin-top: auto;
}
.card .text :nth-last-child(2) {
margin-bottom: 0.75rem;
}
```
--------------------------------
### Enhance Layout with CSS Grid
Source: https://inclusive-components.design/cards
Uses @supports to provide a responsive grid layout for cards while maintaining a fallback for older browsers.
```css
.card .text {
max-width: 60ch;
}
.card + .card {
margin-top: 1.5rem;
}
@supports (display: grid) {
.cards > ul {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr));
grid-gap: 1.5rem;
}
.card + .card {
margin-top: 0;
}
}
```
--------------------------------
### Toggle Interface Visibility with CSS Media Queries
Source: https://inclusive-components.design/data-tables
Uses media queries to switch between table and list views based on viewport width.
```css
@media (min-width: 400px) {
.table-container {
display: block;
}
.lists-container {
display: none;
}
}
```
--------------------------------
### Handle URL Hash Navigation
Source: https://inclusive-components.design/rss
Checks the URL hash on component initialization to automatically expand the section and focus the button if it matches the component's ID.
```javascript
connectedCallback() {
if (window.location.hash.substr(1) === this.heading.id) {
this.setAttribute('open', 'true')
this.btn.focus()
}
}
```
--------------------------------
### Implementing a true menu button
Source: https://inclusive-components.design/rss
Shows the structure of a menu button component using aria-haspopup and aria-expanded, with menu items defined as buttons.
```html
Difficulty
▾
Easy
Medium
Incredibly Hard
```
--------------------------------
### Initialize Component State
Source: https://inclusive-components.design/rss
Setting the initial active state within the component constructor.
```javascript
constructor(props) { super(props); this.state = { active: 'false' }; }
```
--------------------------------
### Static Todo List Structure
Source: https://inclusive-components.design/a-todo-list
A semantic HTML structure for a todo list using an unordered list container to ensure screen reader compatibility.
```html
My Todo List
Pick up kids from school
Learn Haskell
Sleep
```
--------------------------------
### Basic Todo Input Form
Source: https://inclusive-components.design/a-todo-list
A standard form structure for adding todo items, ensuring reliable 'Enter' key submission behavior.
```html
```
--------------------------------
### Associate call-to-action with aria-describedby
Source: https://inclusive-components.design/cards
Link the call-to-action text to the heading using aria-describedby to provide context to screen reader users.
```html
Ten common pitfalls to avoid when designing card components.
read more
By Heydon Pickering
```
--------------------------------
### Apply saved theme on mount
Source: https://inclusive-components.design/a-theme-switcher
Retrieve the stored theme preference when the component mounts.
```javascript
componentDidMount() {
if (this.store) {
this.setState({
active: this.store.getItem('ThemeSwitch') || false
});
}
}
```
--------------------------------
### Apply Basic CSS Theme Inversion
Source: https://inclusive-components.design/rss
Sets a root background color and inverts the colors of the entire page.
```css
:root { background-color: #fefefe; filter: invert(100%); }
```
--------------------------------
### Basic Navigation Structure
Source: https://inclusive-components.design/rss
A standard navigation menu structure intended for use when JavaScript is unavailable.
```html
```
--------------------------------
### Set default hash on page load
Source: https://inclusive-components.design/tabbed-interfaces
JavaScript to ensure a default section is active when the page first loads.
```javascript
// Choose the default section on page load
// And scroll to the top to show nav
window.onload = function () {
window.location.hash = 'section1'
document.documentElement.scrollTop = 0
}
```
--------------------------------
### Define the ToggleSection Web Component
Source: https://inclusive-components.design/collapsible-sections
Initializes the custom element and attaches the Shadow DOM using a template.
```javascript
class ToggleSection extends HTMLElement {
constructor() {
super()
this.attachShadow({ mode: 'open' })
this.shadowRoot.appendChild(tmpl.content.cloneNode(true))
}
}
```
--------------------------------
### Update live region content via JavaScript
Source: https://inclusive-components.design/rss
Listen for menu selection events and update the text content of the live region to notify users.
```javascript
exampleMenuButton.addEventListener('choose', function (e) { // Get the node's text content (label) var choiceLabel = e.details.choice.textContent; // Get the live region node var liveRegion = document.getElementById('menuFeedback'); // Populate the live region liveRegion.textContent = `Your difficulty level is ${choiceLabel}`; }):
```
--------------------------------
### Apply flexbox layout to gallery
Source: https://inclusive-components.design/a-content-slider
Configures the gallery container and list items to display slides at full width.
```css
[aria-label="gallery"] ul {
display: flex;
}
[aria-label="gallery"] li {
list-style: none;
flex: 0 0 100%;
}
```
--------------------------------
### Basic Notification List Structure
Source: https://inclusive-components.design/rss
Initial structure for a notification list using buttons for toggling states.
```html
Notifications Notify by email on off Notify by SMS on off Notify by fax on off Notify by smoke signal on off
```
--------------------------------
### Implement basic collapsible markup
Source: https://inclusive-components.design/rss
Use a button element inside a heading to ensure the interaction is communicated to assistive technology.
```html
My section Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras efficitur laoreet massa. Nam eu porta dolor. Vestibulum pulvinar lorem et nisl tempor lacinia.
Cras mi nisl, semper ut gravida sed, vulputate vel mauris. In dignissim aliquet fermentum. Donec arcu nunc, tempor sed nunc id, dapibus ornare dolor.
```
--------------------------------
### State Helper Functions
Source: https://inclusive-components.design/rss
Functions to check and toggle the current theme state.
```javascript
isActive = () => this.state.active; toggle = () => { this.setState({ active: !this.isActive() }); }
```
--------------------------------
### Manage focus on view elements
Source: https://inclusive-components.design/tabbed-interfaces
Apply the region role and tabindex to view containers to allow programmatic focus management.
```html
...
```
--------------------------------
### Render mobile-friendly definition list
Source: https://inclusive-components.design/rss
Transforms table data into a series of definition lists for narrow viewports, using React Fragments to avoid unnecessary wrapper elements.
```jsx
{this.props.caption} {this.props.rows.map((row, i) =>
{row[0]} {this.props.headers.map((header, i) => i > 0 && {header} {row[i]} )} )}
```
--------------------------------
### Implement basic collapsible sections with JavaScript
Source: https://inclusive-components.design/rss
A minimal script to toggle the visibility of sections based on aria-expanded attributes.
```javascript
(function() { const headings = document.querySelectorAll('h2') Array.prototype.forEach.call(headings, heading => { let btn = heading.querySelector('button') let target = heading.nextElementSibling btn.onclick = () => { let expanded = btn.getAttribute('aria-expanded') === 'true' || false btn.setAttribute('aria-expanded', !expanded) target.hidden = expanded } }) })()
```
--------------------------------
### Handle URL hash on component load
Source: https://inclusive-components.design/collapsible-sections
Use connectedCallback to check for a matching hash and expand the section automatically.
```javascript
connectedCallback() {
if (window.location.hash.substr(1) === this.heading.id) {
this.setAttribute('open', 'true')
this.btn.focus()
}
}
```