Execute a JavaScript when an input field gets focus:
More "Try it Yourself" examples below.
The onfocus event occurs when an element gets focus.
The onfocus event is most often used with <input>, <select>, and <a>.
Tip: The onfocus event is the opposite of the onblur event.
Tip: The onfocus event is similar to the onfocusin event. The main difference is is that the onfocus event does not bubble. Therefore, if you want to find out whether an element or its child gets the focus, you could use the onfocusin event. However, you can achieve this by using the optional useCapture parameter of the addEventListener() method for the onfocus event.
Event | |||||
---|---|---|---|---|---|
onfocus | Yes | Yes | Yes | Yes | Yes |
In HTML:
In JavaScript:
In JavaScript, using the addEventListener() method:
Note: The addEventListener() method is not supported in Internet Explorer 8 and earlier versions.
Bubbles: | No |
---|---|
Cancelable: | No |
Event type: | FocusEvent |
Supported HTML tags: | ALL HTML elements, EXCEPT: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title> |
DOM Version: | Level 2 Events |
Using "onfocus" together with the "onblur" event:
Event delegation: setting the useCapture parameter of addEventListener() to true:
Event delegation: using the focusin event (not supported by Firefox):