'Which HTML elements do I use for a click event?

Recently, I came across this issue I was working on one of the projects and in the theme, it is using a click function on a <span> tag. It was working fine on all browsers except Safari. I did some research and found out a lot of people faced this kind of issue on Safari.

I resolved my issue using role="button" on <span class="menuOpen" role="button">Menu</span> based on the information found here: Click event on <span> or <div> tag not working safari issue

But this problem made me wonder what elements we can use for "click" events.

As per my knowledge, we can add click events on almost all elements, but per the HTML standard, we should add click events only on <a> or <button> tags.

Are there any other HTML elements we should use to trigger a click event?



Solution 1:[1]

There are (currently) a total of 5 HTML elements that can be used by default as a 'clickable' element:

  • Buttons (any type)
  • Inputs type;
    • Button
    • Radio
    • Checkbox
    • Range
    • Reset
    • Submit
    • Image
  • Labels
  • Selects
  • Anchors (though I would discourage this because of the intended behaviour)

You can find a reference of HTML Elements at Mozilla Developer | HTML Elements Reference | Example.

Technically you can make any element clickable by modifying the elements global .onclick attribute, Mozilla provides an example of this here Mozilla Developer | GlobalEventHandlers.onclick. Though if you do this please ensure you also modify the elements role attribute to role=button (as was stated in OPs question), this allows assistive technologies to find the element. A list of ARIA attributes (including the button role) can be found at Mozilla Developer | Using ARIA: Roles, states, and properties

The W3Cs Web Content Accessibility Guidelines also outlines certain elements that should be used for keyboard interactions with Assistive Technologies W3C | WCAG | Using HTML form controls and links, though for this question I believe any element under the roles:

  • grouping
  • editable text

can be ignored.

Solution 2:[2]

function Menu() {
  console.log('Show Menu');
  $('.menuBar').toggleClass('d-none');
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">


<span Onclick="Menu()" class="menuOpen">Menu</span>
<ul class="d-none menuBar">
  <li>Action 1</li>
  <li>Action 2</li>
  <li>Action 3</li>
  <li>Action 4</li>
</ul>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TylerH
Solution 2 Dr. Kitty