Events
onfocus
An element receives focus, through user interaction or a script. HTML event-handler content attribute or corresponding event-handler property; the event fires only on relevant targets. The example uses document.getElementById("demo"). Event interface: FocusEvent. For the described native event: bubbles: no; cancelable: no. Use focusin for bubbling delegation; focus does not necessarily mean the control was activated. Example: Tab into and out of the field. The event listener is registered with addEventListener(), which avoids inline script handlers and supports multiple listeners. Inline handlers require a CSP that permits them; do not insert untrusted code into handler attributes.
Formal Syntax & Structure
html syntaxhtml
<input onfocus="handleEvent(event)">target.addEventListener("focus", event => { /* handle event */ });Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| onfocus | JavaScript handler body | Optional HTML event-handler code; the example uses a registered listener instead. Not a Boolean attribute. |
| event | FocusEvent | Event object delivered to the addEventListener callback; event.type is "focus". Inspect target, currentTarget, bubbles and cancelable as appropriate. |
Working Example
Example Snippethtml
<label for="demo">Sample text</label><input id="demo" value="Example text"><p role="status" id="log">Waiting for focus</p><script> const target = document.getElementById("demo"); const log = document.getElementById("log"); target.addEventListener("focus", event => { log.textContent = String(event.type); });</script>