English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The onfocus attribute is used to get or set the event handler function for the focus event of the current element. The focus event is triggered when the current element receives keyboard focus.
Run the script when the input field receives focus:
<!DOCTYPE html> <html> <head> <title>Use of HTML onfocus event attribute (Basic Tutorial Website oldtoolbag.com)<//title> <script> function setStyle(x) { document.getElementById(x).style.background="yellow"; } </script> </head> <body> <p>When the input field receives focus, the setStyle function is triggered. This function changes the background color of the input field.</p> The first name: <input type="text" id="fname" onfocus="setStyle(this.id)"><br> The last name: <input type="text" id="lname" onfocus="setStyle(this.id)"> </body> </html>Test it out ‹/›
IEFirefoxOperaChromeSafari
All major browsers support the onfocus event attribute
The onfocus attribute is triggered when the element gains focus.
Onfocus is usually used with <input>, <select>, and <a>.
Tip:The attribute event opposite to onfocus isonblur .
Note: The onfocus attribute cannot be used on the following elements: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, or <title>.
None.
<element onfocus="script">
Value | Description |
---|---|
script | Specifies the script to be executed when the onfocus event is triggered |