W3cubDocs

/Web APIs

GlobalEventHandlers.onfocus

The onfocus property of the GlobalEventHandlers mixin is an event handler that processes focus events on the given element.

The focus event is raised when the user sets focus on an element.

For onfocus to fire on non-input elements, they must be given the tabindex attribute (see Building keyboard accessibility back in for more details).

Note: The opposite of onfocus is onblur.

Syntax

target.onfocus = functionRef;

Value

functionRef is a function name or a function expression. The function receives a FocusEvent object as its sole argument.

Example

This example uses onblur and onfocus to change the text within an <input> element.

HTML

<input type="text" value="CLICK HERE">

JavaScript

let input = document.querySelector('input');

input.onblur = inputBlur;
input.onfocus = inputFocus;

function inputBlur() {
  input.value = 'Focus has been lost';
}

function inputFocus() {
  input.value = 'Focus is here';
}

Result

Try clicking in and out of the form field, and watch its contents change accordingly.

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
onfocus
1
12
9
9
≤12.1
1
1
18
9
≤12.1
1
1.0

In contrast to IE, in which almost all kinds of elements receive the focus event, almost all kinds of elements on Gecko browsers do NOT work with this event.

See also

© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onfocus