Execute a script when the 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: 01-Jun-2020

192 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements