Why you should not use div as clickable element
Avoid using adding click listener on divs
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?
- Accessibility Issues (Space or Enter won’t trigger button click)
- Element Won’t be focusable via pressing Tab Key
Workaround
We have to programatically add all these features each time we are creating a clickable div
button
A code snippet from reactJS.
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:
- It comes with default styling.
We can unset existing CSS by setting each property value tounset
or
we can addall: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 issubmit.
Whenever you use button, if it’s not inside a form always add
type='button'
, becausesubmit
andreset
works with form. - No
divs
inside button tag - We still have to add
cursor:pointer
in order to change the cusror to hand.