Blog>
Snippets

Building Accessible UI Components

Code a UI component with proper ARIA attributes to ensure accessibility, reflecting the importance of inclusive design for career growth.
const button = document.createElement('button');

button.setAttribute('role', 'button');
button.setAttribute('aria-label', 'Submit form');
button.textContent = 'Submit';
button.addEventListener('click', () => {
    // Submit form logic here
});

document.body.appendChild(button);
This code creates a button element, sets ARIA attributes to describe its role and accessible name, and appends it to the body of the document. The button has an event listener to handle the click event.
const modal = document.createElement('div');
const modalContent = document.createElement('div');

modal.setAttribute('role', 'dialog');
modal.setAttribute('aria-labelledby', 'dialogTitle');
modal.setAttribute('aria-modal', 'true');
modal.setAttribute('tabindex', '-1'); // Makes the modal focusable
modal.style.display = 'none'; // Hide the modal by default

modalContent.setAttribute('id', 'dialogTitle');
modalContent.textContent = 'Important message';
modal.appendChild(modalContent);

function openModal() {
    modal.style.display = 'block';
    modal.setAttribute('aria-hidden', 'false');
    modal.focus();
}

function closeModal() {
    modal.style.display = 'none';
    modal.setAttribute('aria-hidden', 'true');
}

document.body.appendChild(modal);
This code creates a modal dialog with proper ARIA attributes. The modal is hidden by default. Functions to open and close the modal affect its display property and 'aria-hidden' attribute, ensuring screen readers perceive its state correctly.