Focus and accessible navigation
Quick answer
Focus identifies the element receiving keyboard input. document.activeElement reports the focused element within the document context. element.focus() requests focus; it may fail if the element is not focusable. focus and blur do not bubble, while focusin and focusout do. Keep the visible focus indicator and avoid positive tabindex values that impose an unexpected order. A tabindex of -1 usually permits programmatic focus while excluding an otherwise nonfocusable element from sequential tab navigation.
Browser examples
Run each snippet in a fresh browser document. These are static code blocks; ByteMind browser execution is not verified. Storage examples require a test origin.
const b=document.createElement("button");b.textContent="Save";document.body.append(b);b.focus();console.log(document.activeElement===b);Expected console output:
trueThe connected native button can receive focus.
const p=document.createElement("div"),b=document.createElement("button");b.textContent="Next";p.append(b);document.body.append(p);p.addEventListener("focusin",e=>console.log(e.target===b));b.focus();Expected console output:
trueThe ancestor receives focusin from the button.
Common mistake
Do not move focus on every small content update. Move it intentionally when context changes or the previously focused element disappears.
Practice
Create two labeled inputs and use Tab to test the natural focus order; then observe focusin on their shared parent.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Focus and accessible navigation — Knowledge Check
Apply the concept and predict the browser example behavior.
Which event bubbles when focus enters a descendant?
What does tabindex="-1" usually allow on an otherwise nonfocusable element?
When should focus normally move automatically?
What is the exact console output in Focus and accessible navigation example 1?
const b=document.createElement("button");b.textContent="Save";document.body.append(b);b.focus();console.log(document.activeElement===b);What is the exact console output in Focus and accessible navigation example 2?
const p=document.createElement("div"),b=document.createElement("button");b.textContent="Next";p.append(b);document.body.append(p);p.addEventListener("focusin",e=>console.log(e.target===b));b.focus();