Anchor tags are regularly used to handle page click events and are accessible by default. Visitors unable to use a mouse, for example, can press the tab key on the keyboard to navigate individual links on a page and can typically press the return/enter key to perform a ‘click’ on a selected anchor link. On some of our sites, however, we show/hide text in response to a mouse click on an accordion div element and not anchor tags which leaves visitors without tab and return/enter key functionality.
This issue was addressed by first copying and renaming a classy field twig template down from core into the custom theme and adding a tabindex=‘0’ attribute to each accordion div item. This sweet attribute and value pair sets the element’s position in the tab order of the page relative to the elements around it. This means that as a user tabs down through the page content the divs get focus in a logical sequence. A simple cache flush and voila! Tabbing functionality complete!
With tabbing in place, the return/enter key ‘click’ functionality was coded in next. To achieve this a jQuery keypress event listener was added to the same div items in the site’s javascript file. The handler function first checks for a keycode equal to 13 off the div’s event object, and if true will broadcast a click event from the div element to mimic a mouse click. With just a few lines of code the return/enter key can now ‘click’ more than just anchor tags, and invoke any click event listeners written to respond to true mouse clicks.
In summary, a twig template modification added tabbing capability to the accordion and with just a few lines of javascript we invoked a click event listener on a return/enter keypress event to show/hide accordion content. Now accordions are accessible to everyone and that’s pretty great.