Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 2 min read

A div with onClick is not a button

The Pay button looks fine and works with a mouse. A customer who uses the keyboard presses Tab, and focus jumps straight past it. A screen reader reads the label as plain text. Neither of them can pay, and neither of the

The Pay button looks fine and works with a mouse. A customer who uses the keyboard presses Tab, and focus jumps straight past it. A screen reader reads the label as plain text. Neither of them can pay, and neither of them files a bug report. They leave.

Why it happens

A <button> gets three things from the browser for free: it sits in the Tab order, Enter and Space press it, and assistive technology announces it as a button. A <div> or <span> gets none of them. Adding onClick only handles the mouse.

// Mouse only
<div className="pay-button" onClick={handlePay}>
  Pay now
</div>

The fix: use a real button

Swap the element. Set type="button" so it does not submit a surrounding form by accident, and keep a visible focus style so keyboard users can see where they are.

<button type="button" className="pay-button" onClick={handlePay}>
  Pay now
</button>
.pay-button { all: unset; cursor: pointer; }
.pay-button:focus-visible { outline: 2px solid #34d399; outline-offset: 2px; }

If the click goes to another page, use a link (<a href> or your framework's Link) instead. Links also work with the keyboard and open in a new tab.

When you cannot change the element

Sometimes a library renders the wrapper for you. Then add what the browser would have given a button: a role, a place in the Tab order, and a key handler for Enter and Space.

<div
  role="button"
  tabIndex={0}
  onClick={handlePay}
  onKeyDown={(e) => {
    if (e.key === 'Enter' || e.key === ' ') {
      e.preventDefault(); // stop Space from scrolling the page
      handlePay();
    }
  }}
>
  Pay now
</div>

Check it before you ship

Put the mouse away and go through your main flow (sign up, checkout, settings) with Tab, Shift+Tab, Enter and Space. Every action must be reachable, and you must always see where the focus is.

In code, the jsx-a11y ESLint rules click-events-have-key-events and no-static-element-interactions catch the same pattern. A release check can do the same on the pull request: Zelsis flags a div or span with onClick and no role, tabIndex or key handler (rule 1029), and suggests the button fix.

We wrote this up as a guide too: https://zelsis.com/guides/clickable-div-keyboard

Related: we ran this kind of check on our own UI last week and it flagged one thing that was wrong. How that went: https://dev.to/bedirhandev/we-ran-our-own-form-label-check-on-our-own-ui-it-flagged-one-thing-and-it-was-wrong-pab

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.