Skip to content
Related Articles

Related Articles

HTML | DOM onfocus Event
  • Last Updated : 28 Jun, 2019

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
My Personal Notes arrow_drop_up
Recommended Articles
Page :