What is Keydown event Listener in javascript?

Rumman Ansari   Software Engineer   2023-03-26   211 Share
☰ Table of Contents

Table of Content:


The "keydown" event in JavaScript is triggered when a key is pressed down on the keyboard. You can use an event listener to execute a function when the "keydown" event occurs on an element.

Here is an example of using an event listener to execute a function when a key is pressed down on the keyboard:


<input type="text" id="myInput">

<script>
  // Define the function to be executed when a key is pressed down on the keyboard
  function keyPressed(event) {
    console.log("Key was pressed down: " + event.key);
  }

  // Attach the function as an event listener to the "keydown" event on the input field
  document.getElementById("myInput").addEventListener("keydown", keyPressed);
</script>

In this example, the function keyPressed is defined and is attached as an event listener to the "keydown" event on the input field with the ID "myInput". When a key is pressed down on the keyboard, the function will be executed and the key that was pressed will be logged to the console.

Event listeners are a powerful tool for creating interactive and dynamic webpages. They can be attached to a wide range of events on different elements, such as mouse clicks, keyboard input, form submissions, and more.


Copy and paste below code and try it


<!DOCTYPE html>
<html>
<body> 
 <h2>Example of keydown event Listener in javascript</h2>
 <input type="text" id="myInput">  
</body>
</html>  

<script>
  // Define the function to be executed when a key is pressed down on the keyboard
  function keyPressed(event) {
    console.log("Key was pressed down: " + event.key);
    alert(event.key)
  }

  // Attach the function as an event listener to the "keydown" event on the input field
  document.getElementById("myInput").addEventListener("keydown", keyPressed);
</script>

You can also try below Code:


<!DOCTYPE html>
<html>
<body>

<p>This example uses the addEventListener() method to attach a "keydown" event to an input element.</p>

<p>Press a key inside the text field to set a red background color.</p>

<input type="text" id="demo">

<script>
document.getElementById("demo").addEventListener("keydown", myFunction);

function myFunction() {
  document.getElementById("demo").style.backgroundColor = "red";
}
</script>

</body>
</html>