onfocusEvent

事件对象参考手册Event object

Examples

Execute a piece of JavaScript code when the input field gets focus:

<input type="text" onfocus="myFunction()">

Try it yourself »

Definition and Usage

The onfocus event occurs when an object gains focus.

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

Tip:The opposite event of the onfocus event isonblurevent.

Syntax

In HTML:

<element onfocus="SomeJavaScriptCode">

In JavaScript:

object.onfocus=function(){SomeJavaScriptCode}

In JavaScript, using the addEventListener() method:

object.addEventListener("focus", myScript);Try it yourself

Parameter Description
SomeJavaScriptCode Required. Specifies the JavaScript to execute when the event occurs.


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support the onfocus event


HTML tags that support the onfocus event:

The onfocus attribute is usually used on all HTML elements, except: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title>.


事件对象参考手册Event object Other extensions