CKTIS / HTML
onfocus — handling focus acquisition
The onfocus attribute contains JavaScript executed when a focus event is received. It lets you respond when an input gains focus, but does not itself make an element focusable.
Version: WHATWG HTML Living Standard; index snapshot date recorded separately
Syntax
onfocus="JavaScript statements"onfocus is an event-handler attribute for focus. Its value is a JavaScript function body, not an event name or a Boolean value. On body and frameset, it handles focus of the Window object rather than the element itself.
Focus identifies the destination for keyboard input. An input can gain it through Tab navigation or focus(). Adding onfocus alone does not make an element focusable. The focus event does not bubble and cannot be canceled; return false does not prevent focus acquisition.
The HTML attribute and the JavaScript property element.onfocus configure the same handler. Content Security Policy can block code written directly in the attribute. Do not insert untrusted text into it as code.
In the example, move focus to the input using Tab. The text Waiting changes to Focused. Preserve a visible focus indicator so keyboard users can identify the active element.
Examples
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>onfocus example</title>
<label for="name">Name</label>
<input id="name" onfocus="document.getElementById('status').textContent = 'Focused';">
<p id="status">Waiting</p>
</html>Result
Focused
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.