If we don't manually set any of the HTML elements to be focused using javascript, how does HTML decide which element to be focused?
-
in http://stackoverflow.com/questions/4166423/default-html-form-focus-without-javascript – Álvaro Touzón Feb 14 '17 at 10:39
-
1It follows the document's flow? – user7393973 Feb 14 '17 at 10:40
4 Answers
It is done via tabindex attribute. By default it goes through focusable elements by position in page, but you can modify this behaviour.
From linked article:
Focusing non focusable elements:
tabindex=0
When tabindex is set to 0, the element is inserted into the tab order based on its location in the source code. If the element is focusable by default there’s no need to use tabindex at all, but if you’re repurposing an element like a span or div, then tabindex=0 is the natural way to include it in the tab order.
Ignore some focusable elements:
tabindex=-1
When tabindex is set to a negative integer like -1, it becomes programmatically focusable but it isn’t included in the tab order.
And finally: choose by yourself the order, no matter position of the element:
tabindex=1+
It imposes a tab order on the content that bears no resemblance to the expected tab order.

- 1
- 1

- 26,609
- 8
- 70
- 109
If you mean "What tells the browser which elements can be focused?" then you are looking for the tabindex
attribute. Adding this to an element will allow an input device (i.e. mouse, keyboard) to trigger a focus state on the element.
If your question is basically, "how are things focused on?", this is done using an input device, i.e. mouse, and keyboard.

- 813
- 1
- 7
- 16
if you mean when the page loads you can use the autofocus attribute
<input type="text" autofocus>

- 69
- 2
- 9
There is actually no element that gets the focus by default.
We can check this pretty easily by creating a simple site and log
document.querySelectorAll(":focus")
to the console.
You will see that it will return an empty array, meaning that no element is focused.

- 499
- 3
- 12