|
| 1 | +# onclick-has-focus |
| 2 | + |
| 3 | +Enforce that visible elements with onClick handlers must be focusable. Visible means that it is not hidden from a screen reader. Examples of non-interactive elements are `div`, `section`, and `a` elements without a href prop. Elements which have click handlers but are not focusable can not be used by keyboard-only users. |
| 4 | + |
| 5 | +To make an element focusable, you can either set the tabIndex property, or use an element type which is inherently focusable. |
| 6 | + |
| 7 | +Elements that are inherently focusable are as follows: |
| 8 | +- `<input>`, `<button>`, `<select>` and `<textarea>` elements which are not disabled |
| 9 | +- `<a>` or `<area>` elements with an `href` attribute. |
| 10 | + |
| 11 | +#### References |
| 12 | +1. [AX_FOCUS_02](https://github.com/GoogleChrome/accessibility-developer-tools/wiki/Audit-Rules#ax_focus_02) |
| 13 | +2. [MDN](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_button_role#Keyboard_and_focus) |
| 14 | + |
| 15 | +## Rule details |
| 16 | + |
| 17 | +This rule takes no arguments. |
| 18 | + |
| 19 | +### Succeed |
| 20 | +```jsx |
| 21 | +<!-- Good: div with onClick attribute is hidden from screen reader --> |
| 22 | +<div aria-hidden onClick={() => void 0} /> |
| 23 | +<!-- Good: span with onClick attribute is in the tab order --> |
| 24 | +<span onClick="doSomething();" tabIndex="0">Click me!</span> |
| 25 | +<!-- Good: span with onClick attribute may be focused programmatically --> |
| 26 | +<span onClick="doSomething();" tabIndex="-1">Click me too!</span> |
| 27 | +<!-- Good: anchor element with href is inherently focusable --> |
| 28 | +<a href="javascript:void(0);" onClick="doSomething();">Click ALL the things!</a> |
| 29 | +<!-- Good: buttons are inherently focusable --> |
| 30 | +<button onClick="doSomething();">Click the button :)</a> |
| 31 | +``` |
| 32 | + |
| 33 | +### Fail |
| 34 | +```jsx |
| 35 | +<!-- Bad: span with onClick attribute has no tabindex --> |
| 36 | +<span onclick="submitForm();">Submit</span> |
| 37 | +<!-- Bad: anchor element without href is not focusable --> |
| 38 | +<a onclick="showNextPage();">Next page</a> |
| 39 | +``` |
0 commit comments