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.
document.activeElement corresponds to the currently focused element.
<input type="text"> document.querySelector("input").focus(); console.log(document.activeElement.tagName); //!INPUT document.querySelector("input").blur(); console.log(document.activeElement.tagName); //!BODY </script>
<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
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.