Make Any HTML Tag Selectable Using the Tab Key for Accessibility

Website accessibility is getting more and more important these days. One of the key factors in web accessibility is the ability to access all of the features of the website with the keyboard. If any element is clickable with a mouse, it needs to be reachable by keyboard using the tab key and return/enter to “click” it.

HTML links automatically work this way. But, if you have, say, a div that performs some function when clicked via a JavaScript click handler, that element won’t by default be reachable by using the tab key, and won’t be “clickable” using a keyboard. In other words, it won’t be compliant with today’s accessibility laws.

How to Make Any HTML Tag Reachable With the Tab Key

The first step is to make the element reachable by using the tab key. That is really easy to do. Simply attach the “tabindex” attribute to the element with a value of zero. So, for a div, it would look like this:

<div tabindex="0"> Your Content </div>

The value of the tabindex forces the order in which the tab key can reach these elements. For accessibility purposes, you should always just set the value to zero because setting a positive value actually makes it more difficult for people using assistive technology to navigate the page.

Now, when you load the page and press the tab key, the element should be one of the “stops” as you step through all of the links using the tab key.

How to Make the Tag “Clickable” Using the Return/Enter Key

OK, the HTML element is now reachable using the tab key but nothing happens when you stop on it at press the Return or Enter key. Making this work requires some JavaScript:

jQuery( document ).on( "keypress", "#your_div_id", function(e) {
  if (e.which == 13) 
    { 
    alert( "Div has been clicked using the keyboard" ); 
    }
});

Replace “#your_div_id” with your element’s selector. And of course, replace the alert with whatever you want to happen when the user clicks the element using the keyboard.

That should do it! Let me know if you have any questions or comments! – Brian



Leave a Comment or Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.