The fields can get keyboard focus when clicked or activated in some other way, they to become the currently active element. If a document has a text field, text typed will end up in there only when the field is focused. Other fields respond differently to keyboard events.

For example, a <select> menu tries to move to the option that contains the text the user typed and responds to the arrow keys by moving its selection up and down.

We can control focus from JavaScript with the focus and blur methods. The first moves focus to the DOM element it is called on, and the second removes focus. The value in document.activeElement corresponds to the currently focused element.

<input type="text">


JavaScript can be used to focus this field when the document is loaded, but HTML also provides the autofocus attribute.

<input type ="text" autofocus>

Browsers allow the user to move the focus through the document by pressing the Tab key. We can set the order in which elements receive focus with the tabindex attribute.

The following example document will let focus jump from the text input to the OK button, rather than going through the help link first:

<input type="text" tabindex=1><a href=".">(help)</a>

<button onclick="console.log('ok')" tabindex=2>OK</button>

By default, most types of HTML elements cannot be focused. But you can add a tabindex attribute to any element, which will make it focusable.

Related Tutorial
Follow Us #
Contents +