Visible, non-interactive elements with click handlers must have at least one keyboard listener

Explanation:

When developing accessible websites or applications, it is important to ensure that all elements that are visible but not interactive have at least one keyboard listener. This is to ensure that keyboard-only users can still interact with these elements and receive feedback when they are clicked.

Here is an example to demonstrate this:

      
         <div tabindex="0" onclick="handleClick()" onkeypress="handleKeyPress(event)">
            Click me
         </div>

         <script>
            function handleClick() {
               // Perform necessary actions when the element is clicked
            }

            function handleKeyPress(event) {
               if (event.key === 'Enter' || event.key === ' ') {
                  handleClick();
               }
            }
         </script>
      
   

In the example above, we have a div element that is made focusable by setting the tabindex attribute to “0”. This allows keyboard users to navigate to the div using the Tab key. We have also attached an onclick event handler to handle the click event and perform the necessary actions.

To make the element accessible via the keyboard, we have added an onkeypress event handler that checks for the Enter key or the Space key being pressed. When either of these keys is pressed, the handleKeyPress function is called, and if the condition is met, it triggers the same action as the onclick event.

By including both a click handler and a keyboard listener, we ensure that the element is accessible to users of different input methods.

Related Post

Leave a comment