HTML | DOM onfocus Event
The HTML DOM onfocus event occurs when an element gets focus. The onfocus event is mostly used with <input>, <select>, and <a>. The onfocus event is the opposite of the onblur event.
The HTML DOM onfocus event support all HTML tag EXCEPT:
- <base>
- <bdo>
- <br>
- <head>
- <html>
- <iframe>
- <meta>
- <param>
- <script>
- <style>
- <title>
Syntax:
- In HTML:
<element onfocus="myScript">
- In JavaScript:
object.onfocus = function(){myScript}; - In JavaScript, using the addEventListener() method:
object.addEventListener("focus", myScript);
Note: The onfocus event different from onfocusin event, because the onfocus event does not bubble.
Example 1:
<!DOCTYPE html> <html> <head> <title> HTML DOM onfocus Event </title> </head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <h2> HTML DOM onfocus Event </h2> <br> Name: <input type="text" onfocus="geekfun(this)"> <script> function geekfun(gfg) { gfg.style.background = "green"; } </script> </center> </body> </html> |
Output:

Example 2:
<!DOCTYPE html> <html> <head> <title> HTML DOM onfocus Event </title> </head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <h2>HTML DOM onfocus Event</h2> <br> Name: <input type="text" id="fname"> <script> document.getElementById( "fname").onfocus = function() { geekfun() }; function geekfun() { document.getElementById( "fname").style.backgroundColor = "green"; } </script> </center> </body> </html> |
Output

Example 3:
<!DOCTYPE html> <html> <head> <title> HTML DOM onfocus Event </title> </head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <h2>HTML DOM onfocus Event</h2> <br> Name: <input type="text" id="fname"> <script> document.getElementById( "fname").addEventListener( "focus", Geeksfun); function Geeksfun() { document.getElementById( "fname").style.backgroundColor = "green"; } </script> </center> </body> </html> |
Output:

Supported Browsers: The browsers supported by HTML DOM onfocus Event are listed below:
- Google Chrome
- Internet Explorer
- Firefox
- Apple Safari
- Opera
Recommended Posts:
- HTML | onfocus Event Attribute
- HTML | DOM oncopy Event
- HTML | DOM oncut Event
- HTML | DOM ondblclick Event
- HTML | DOM onchange Event
- HTML | DOM ontoggle Event
- HTML | DOM oncontextmenu Event
- HTML | DOM onclick Event
- HTML | DOM ondragend Event
- HTML | DOM onstalled Event
- HTML | DOM onmouseleave Event
- HTML | DOM ondrop Event
- HTML | DOM ondurationchange Event
- HTML | DOM ondragstart Event
- HTML | DOM ondragenter Event
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


