HTML onfocus Attribute

Beginner
⏱️ 5 min read
📚 Updated: Jun 2026
🎯 3 Examples
Events & Handlers

Introduction

The onfocus attribute is an inline event handler that runs JavaScript when the focus event fires. That happens when a focusable element receives focus — by mouse click, tap, or keyboard Tab. Common targets include <input>, <textarea>, <select>, <button>, and links. Use it to highlight the active field, show helper text, or prepare validation UI. Pair it with onblur for enter-and-leave flows. The focus event does not bubble; use focusin for delegation on a parent.

What You’ll Learn

01

Event handler

Inline JS.

02

focus event

Gain focus.

03

Form fields

input, button.

04

+ onblur

Enter / leave.

05

addEventListener

Preferred way.

06

Tab key

Keyboard nav.

Purpose of onfocus Attribute

The primary purpose of onfocus is to respond when a user starts interacting with a control. You might highlight the active input, reveal formatting hints, or fetch suggestions for an autocomplete field. Because focus also moves via keyboard, onfocus helps keyboard users get the same feedback as mouse users.

Keep handlers lightweight — heavy work on every focus can feel sluggish. For validation, many apps validate on blur (leave) rather than on every focus, but showing hints on focus is a common pattern.

💡
Prefer addEventListener in production

Use input.addEventListener("focus", handler) instead of inline onfocus when building maintainable forms. CSS :focus and :focus-visible often handle visual states without JavaScript.

📝 Syntax

Set onfocus on a focusable element, or assign element.onfocus:

onfocus.html
<script>
  function highlightInput(el) {
    el.style.outline = "2px solid #2563eb";
  }
</script>

<input type="text" id="name" onfocus="highlightInput(this)">

Syntax Rules

  • Value is JavaScript executed when the focus event fires.
  • Works on focusable elements: input, textarea, select, button, a[href], [tabindex].
  • Triggered by click, tap, Tab, or programmatic element.focus().
  • JavaScript: element.onfocus = function() { … }.
  • Modern alternative: element.addEventListener("focus", handler).
  • focus does not bubble — use focusin for parent delegation.

💎 Values

The onfocus attribute accepts a string of JavaScript code:

  • onfocus="highlightInput()" — Call a named function.
  • onfocus="showHint()" — Inline statement.
  • JavaScript: field.onfocus = () => { … } assigns the handler.
onfocus-js.html
const email = document.getElementById("email");

email.addEventListener("focus", () => {
  document.getElementById("email-hint").hidden = false;
});

email.addEventListener("blur", () => {
  document.getElementById("email-hint").hidden = true;
});

⚡ Quick Reference

Actionfocus fires?Notes
Click into inputYesMost common trigger
Tab to next fieldYesKeyboard navigation
Click outside fieldNo (blur fires)Use onblur
element.focus() in JSYesProgrammatic focus
Handler attributeonfocusInline on element
Bubbles to parent?NoUse focusin

Applicable Elements

TargetSupported?Notes
<input>YesMost common use
<textarea>, <select>YesForm controls
<button>, <a href>YesInteractive elements
tabindex="0" on divYesCustom focusable regions
<div> without tabindexNoNot focusable by default

onfocus vs onblur vs onclick

HandlerWhen it firesTypical use
onfocusElement gains focusHighlight field, show hint
onblurElement loses focusValidate input on leave
onclickPointer activationButton actions, toggles

Examples Gallery

Inline highlight on focus, addEventListener, and pairing with onblur.

👀 Live Preview

Click or Tab into the field — focus adds a blue outline:

Focus the input to see the handler run.

Example — Inline onfocus highlight

Change border style when the input receives focus:

inline-onfocus.html
<input type="text" id="myInput" onfocus="highlightInput()">

<script>
  function highlightInput() {
    document.getElementById("myInput").style.border = "2px solid #2563eb";
  }
</script>
Try It Yourself

How It Works

The browser fires focus when the field becomes active. The inline onfocus attribute wires up the handler.

Dynamic Values with JavaScript

Attach the handler with addEventListener:

dynamic-onfocus.html
<script>
  document.getElementById("dynamicInput").addEventListener("focus", function () {
    console.log("Input is in focus!");
  });

  // Or property form:
  document.getElementById("dynamicInput").onfocus = function () { /* … */ };
</script>
Try It Yourself

How It Works

Register the listener once at page load. Focus from mouse or keyboard triggers the same handler.

Example — Pair with onblur

Show a hint on focus and hide it on blur:

onfocus-blur-pair.html
const field = document.getElementById("email");
const hint = document.getElementById("email-hint");

field.addEventListener("focus", () => {
  hint.hidden = false;
});

field.addEventListener("blur", () => {
  hint.hidden = true;
});
Try It Yourself

How It Works

Focus and blur are complementary events on the same element — ideal for contextual hints without cluttering the default view.

♿ Accessibility

  • Prefer CSS :focus-visible — Show focus rings for keyboard users without noisy outlines on every click.
  • Do not remove focus outlines — If you restyle focus, ensure a visible indicator remains.
  • Avoid alert() on focus — Blocking dialogs on focus harm keyboard and screen reader users.
  • Associate labels — Use <label for> so focus moves predictably when the label is clicked.
  • Logical tab order — Avoid positive tabindex values that confuse navigation.

🧠 How onfocus Works

1

User targets control

Click, tap, or Tab key.

Input
2

Element becomes active

Browser moves focus.

Focus
3

focus fires

onfocus handler runs.

Event
=

Responsive form UX

Hints, highlight, prep work.

Browser Support

The focus event and onfocus handler are supported in all modern browsers on focusable elements — Chrome, Firefox, Safari, and Edge.

DOM Events · Fully supported

Universal onfocus support

All major browsers fire the underlying event and honor the onfocus handler attribute.

99% Browser support
Google Chrome Fully supported
Full support
Mozilla Firefox Fully supported
Full support
Apple Safari Fully supported
Full support
Microsoft Edge Fully supported
Full support
Internet Explorer IE 9+ supported
Full support
Opera Fully supported
Full support
onfocus attribute 99% supported

Bottom line: Use onfocus confidently on form controls; prefer addEventListener and CSS focus styles in production.

💡 Best Practices

✅ Do

  • Pair with onblur for enter-and-leave field behavior
  • Use addEventListener("focus", …) in production code
  • Style focus with CSS :focus-visible when possible
  • Keep handlers fast and non-blocking
  • Test with keyboard Tab navigation

❌ Don’t

  • Use alert() when a field receives focus
  • Remove visible focus indicators entirely
  • Assume focus bubbles (use focusin for delegation)
  • Attach onfocus to non-focusable elements
  • Run heavy validation on every focus event

Conclusion

The onfocus attribute runs JavaScript when a focusable element becomes active — essential for form hints, highlights, and accessible keyboard flows.

Prefer addEventListener("focus", …), pair with onblur, and use CSS for visual focus states whenever you can.

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about onfocus

Bookmark these before building your next interactive form.

5
Core concepts
📝 02

Form fields

input, button.

Scope
03

Tab key

Keyboard too.

A11y
📝 04

+ onblur

Enter / leave.

Pattern
05

focusin

For bubbling.

Delegate

❓ Frequently Asked Questions

It runs JavaScript when the focus event fires — when a focusable element receives focus.
input, textarea, select, button, a[href], and elements with tabindex.
onfocus runs when focus enters. onblur runs when focus leaves. They are often used together.
No. Use focusin with addEventListener if you need delegation on a parent element.
addEventListener("focus", handler) is preferred for production. CSS :focus-visible handles many styling needs without JS.
Yes in all modern browsers on focusable elements.

Master focus events in forms

Practice the onfocus attribute with highlight and hint examples in the Try It editor.

Try onfocus demo →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful