Execute a Script When an Element Gets Focus in HTML



Use the onfocus attribute to execute a script when the element gets focus in HTML.

Example

You can try to run the following code to implement the onfocus attribute −

<!DOCTYPE html>
<html>
   <body>
      <p>Enter subject name below,</p>
      Subject: <input type = "text" id = "sname" onfocus = "display(this.id)">
      <br>

      <script>
         function display(val) {
            document.getElementById(val).style.background = "blue";
         }
      </script>
   </body>
</html>
Updated on: 2020-06-01T10:41:55+05:30

286 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements