HTML onfocus event attribute

Example

Execute JavaScript when the input field gains focus:

<input type="text" id="fname"} onfocus="setStyle(this.id)">

Try It Yourself

Browser Support

IE Firefox Chrome Safari Opera

All major browsers support the onfocus attribute.

Definition and Usage

The onfocus attribute triggers when the element gains focus.

onfocus is commonly used with <input>, <select>, and <a>.

Tip:The onfocus attribute is the opposite of the onblur attribute.

Note:The onfocus attribute is not applicable to the following elements: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style> or <title>.

Differences between HTML 4.01 and HTML5

None.

Syntax

<element onfocus="script">

Attribute Value

Value Description
script Script runs when onfocus occurs.