References

Beginner-friendly references for web development, with live, editable examples.

The HTML onfocus event

Event All modern browsers Updated
Quick answer

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

Live 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 inline onfocus attribute — it separates behavior from markup and allows multiple handlers.
  • Use the bubbling focusin/focusout events 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?
It runs JavaScript when the element gains focus. In JavaScript the event is named focus.
Why does focus (or blur) not work with event delegation?
Because focus and blur do not bubble. Use the bubbling focusin and focusout events instead.
What is the difference between blur and focusout?
They fire at the same moment, but focusout bubbles and blur does not — so focusout works for delegation.
Should I use the onfocus attribute or addEventListener?
Prefer addEventListener('focus', …) in JavaScript. The inline onfocus attribute works but mixes behavior into the markup and allows only one handler per element.