When creating custom checkbox and radio button groups, it’s important to make sure that they’re accessible to all users, including those who use assistive technologies like screen readers. One way to do this is by using the ARIA checked attribute to indicate the state of each checkbox or radio button.
The checked attribute can have one of three values: true, false, or mixed. true indicates that the checkbox or radio button is selected, false indicates that it’s not selected, and mixed indicates that it’s in an indeterminate state (e.g., for a checkbox that represents a group of items where some but not all are selected).
Here’s an example of how to use the checked attribute in HTML and JavaScript to create an accessible checkbox group:
<div role="group" aria-label="Fruit options">
<label>
<input type="checkbox" name="fruit" value="apple" aria-checked="false">
Apple
</label>
<label>
<input type="checkbox" name="fruit" value="orange" aria-checked="false">
Orange
</label>
<label>
<input type="checkbox" name="fruit" value="banana" aria-checked="false">
Banana
</label>
</div>
In this example, we’ve added the aria-checked="false" attribute to each checkbox to indicate that none of them are initially selected.
To handle user interaction with the checkboxes, we can add event listeners to update the aria-checked attribute accordingly. Here’s an example in JavaScript:
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(checkbox => {
checkbox.addEventListener('click', () => {
const isChecked = checkbox.checked;
checkbox.setAttribute('aria-checked', isChecked);
});
});
In this example, we’re adding a click event listener to each checkbox. When a checkbox is clicked, we check its checked property to determine its new state, and then update its aria-checked attribute to match.
Using the checked attribute in this way helps ensure that custom checkbox and radio button groups are accessible to all users, including those who rely on assistive technologies.
Leave a comment