Execute Script on Key Press in HTML



Use the onkeydown attribute. The onkeydown attribute triggers when the user is pressing a key.

Example

You can try to run the following code to execute a script on pressing a key −

<!DOCTYPE html>
<html>
   <body>
      <p>Press a key inside the textbox.</p>
      <input type = "text" onkeydown = "display()">
      <script>
         function display() {
            alert("You pressed a key!");
         }
      </script>
   </body>
</html>
Updated on: 2020-03-03T05:36:03+05:30

327 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements