The HTML onfocus event
The HTML onfocus attribute runs JavaScript when the element receives focus. It is an inline handler for the focus event; in modern code prefer addEventListener('focus', …).
Overview
The onfocus event attribute runs JavaScript when the element gains focus. In JavaScript the event itself is named focus — drop the on prefix when you call addEventListener.
It is a focus event. A useful subtlety: focus and blur do not bubble, so they cannot be used with event delegation. When you need bubbling versions — for example to watch focus changes across a whole form — use their counterparts focusin and focusout.
You can wire this up with the inline onfocus HTML attribute, but the modern, recommended approach is element.addEventListener('focus', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.
Syntax
<element onfocus="handler()">…</element>
element.addEventListener('focus', handler);
Example
<input onfocus="this.style.background='#fef9c3'" onblur="this.style.background=''" placeholder="Focus me" style="padding:8px;">
Best practices
- Prefer
element.addEventListener('focus', handler)over the inlineonfocusattribute — it separates behavior from markup and allows multiple handlers. - Use the bubbling
focusin/focusoutevents when you need event delegation, since focus and blur do not bubble. - Never remove the visible focus indicator without a clear replacement — keyboard users rely on it.
- Use focus handling to enhance forms (inline validation, hints), not to trap or steal focus.
Frequently asked questions
What is the onfocus event?
focus.Why does focus (or blur) not work with event delegation?
focus and blur do not bubble. Use the bubbling focusin and focusout events instead.What is the difference between blur and focusout?
focusout bubbles and blur does not — so focusout works for delegation.Should I use the onfocus attribute or addEventListener?
addEventListener('focus', …) in JavaScript. The inline onfocus attribute works but mixes behavior into the markup and allows only one handler per element.