Why you should not use div as clickable element

Avoid using adding click listener on divs

Photo by Xavi Cabrera on Unsplash

buttons are the most common way to provide interactivity to any web application. But we often tend to use other html elements, like div span etc as a clickable elements.
By doing so we are missing out many in built browser’s feature.

What we are missing?

  1. Accessibility Issues (Space or Enter won’t trigger button click)
  2. Element Won’t be focusable via pressing Tab Key
focused element show with orange border and interactive via space/enter

Workaround

We have to programatically add all these features each time we are creating a clickable div button
A code snippet from reactJS.

div as a button

Better Solution

Always prefer using button as clickable element in order to get all the in built feature of browser, and in case you are not using it, always add above listed accessibility feature to your div.

Although, using button directly isn’t straight forward. We have to add and modify few default CSS and behaviour which comes bundled with the browser.

Caveats of using button:

  1. It comes with default styling.
    We can unset existing CSS by setting each property value to unset or
    we can add all:unset to remove all default styles at once.
    In HTML we have three types of buttons. submit, reset and button.
    The default type of button is submit.
    Whenever you use button, if it’s not inside a form always add
    type='button' , because submit and reset works with form.
  2. No divs inside button tag
  3. We still have to add cursor:pointer in order to change the cusror to hand.
using button as a clickable (ReactJS)

--

--

राहुल मिश्रा
राहुल मिश्रा

Responses (2)