Challenge 2: Fix a Broken Custom Toggle — Possible Solution
====================================================================
THE BROKEN VERSION
--------------------
Show more
WHAT'S MISSING
----------------
- No tabindex="0" — this div is not part of the tab order at all, so a
keyboard-only user can never even reach it, regardless of what role
is announced on it.
- No keydown handler for Enter/Space — even if tabindex were added,
role="button" alone still doesn't give the div any built-in
keyboard-activation behavior; a real handles Enter/Space
automatically, but role="button" on a div is purely an announcement,
exactly as this chapter's "danger of misuse" section describes.
OPTION A: Fix the div to actually work
------------------------------------------
Show more
OPTION B (RECOMMENDED): Use a real button instead
------------------------------------------------------
Show more
WHY OPTION B IS THE BETTER RECOMMENDATION
----------------------------------------------
This chapter's own comparison box makes this exact point: a real
gives tab order and Enter/Space activation automatically, with
NO chance of forgetting one of the manual pieces Option A requires
(tabindex, the keydown handler, calling preventDefault() so Space
doesn't also scroll the page). The ONLY thing this element genuinely
needs beyond what already provides natively is the
aria-expanded state — which is legitimate ARIA usage here, since there
is no native HTML attribute that communicates "this control's
associated content is currently expanded or collapsed." Everything
else about button-like behavior comes from the native element itself,
for free, exactly as Chapter 2 and this chapter's first-rule-of-ARIA
principle both emphasize.
WHY THIS WORKS AS AN ANSWER
------------------------------
Option A demonstrates that the div CAN be made to work correctly, but
only by manually reimplementing everything already does
automatically — several distinct places to get it wrong (forgetting
tabindex, forgetting the keydown handler, forgetting Space's default
scroll behavior). Option B shows the chapter's actual recommended
practice: reach for the native element FIRST, and only add the ARIA
attribute (aria-expanded) that genuinely has no native equivalent.