Make an HTML element non-focusable

Is it possible to make an HTML element non-focusable?

I understand that a list of elements that can receive focus can be defined and that a user can navigate through these elements by pressing a Tab key. I also see that it is up to the browser to control this.

But maybe there is a way to make certain elements non-focusable, say I want a user to skip a certain <a> tag when pressing a Tab.


<a href="http://foo.bar" tabindex="-1">unfocusable</a>

A negative value means that the element should be focusable, but should not be reachable via sequential keyboard navigation.

See also: developer.mozilla.org


To completely prevent focus, not just when using the tab button, set disabled as an attribute in your HTML element.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<input class="form-control" type="text"> Click this, you can see it's focusable.

<input class="form-control" type="text" readonly>  Click this, you can see it's focusable.

<input class="form-control" type="text" readonly tabindex="-1">  Click this, you can see it's focusable. Not tab'able.

<input class="form-control" type="text" disabled>  Click this, you can see it's <strong>not</strong> focusable.

In order to make an prevent an element from taking focus ("non-focusable"), you need to use Javascript to watch for the focus and prevent the default interaction.

In order to prevent an element from being tabbed to, use tabindex=-1 attribute.

Adding tabindex=-1 will make any element focusable, even div elements. This means when a user clicks on it, it would likely get a focus outline, depending on the browser..

You would ideally, want this:

function preventFocus(event) {
  event.preventDefault();
  if (event.relatedTarget) {
    // Revert focus back to previous blurring element
    event.relatedTarget.focus();
  } else {
    // No previous focus target, blur instead
    event.currentTarget.blur();
  }
}

/* ... */

element.setAttribute('tabindex', '-1');
element.addEventListener('focus', preventFocus);

TabIndex is what your looking for: http://www.w3schools.com/jsref/prop_html_tabindex.asp.

When you set a tabIndex value to -1 you will skip it when tabbing through your form.


For the element you do not want to be focused on tab, you have to put the tabindex as a negative value.