Custom Checkbox
If possible, use a native checkbox with custom CSS. If not possible, try to argue for using it. If you just can't because of a particular use case or other reason, then keep reading.
- Add
role="checkbox"
to the element simulating the checkbox (receives click events). - Add
aria-checked="true|false|mixed"
to the same element, matching current checked state. - Add
tabindex="0"
to allow this element to get focus. - Add
cursor:pointer
to the element's styles. - If your checkbox is disabled,
- Add
aria-disabled
- Provide styling to visually indicate the disabled state (e.g., grayed out)
- Set
tabindex="-1"
to prevent focus
- Add
- Listen for these events on the element:
click
and keep track of the value in your internal storekeypress
and let users toggle the checked state and value when pressingSPACE
Example
<fieldset role="group">
<div id="fruit" class="custom-checkbox"
tabindex="0" role="checkbox" aria-checked="mixed"></div>
<label for="fruit">Fruit</label>
<div class="checkbox-group">
<div id="apples" class="custom-checkbox"
tabindex="-1" role="checkbox" aria-checked="true"></div>
<label for="apples">Apples</label>
<div id="bananas" class="custom-checkbox"
tabindex="-1" role="checkbox"
aria-disabled="true" aria-checked="false"></div>
<label for="bananas">Bananas</label>
</div>
</fieldset>
.custom-checkbox {
cursor: pointer;
}
.custom-checkbox[aria-disabled] {
opacity: .5;
pointer-events: none;
}