How to Detect Key Press in Javascript
In this tutorial, you will learn how to detect key press in javascript. Keyboard events are triggered whenever a user interacts on a webpage using a keyboard such as typing some random text in an input field or pressing Enter
key to submit a form.
There are 3 keyboard events keyup
, keypress
, and keydown
. In the case of keyboard events, the event object contains certain properties and that can help us in detecting which key is pressed by the user. In our case, we are going to use the key
property.
In the following example, we have one input field in which we will enter some random text. As we start typing, we will display the letters one by one on the screen. Please have a look over the code example and steps given below.
HTML & CSS
- We have 3 elements in the HTML file (
div
,input
, andh1
). Thediv
element is just a wrapper for the rest of the elements. - The inner text for the
h1
element is“Result”
, which will be later replaced by letters using javascript. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div class="container"> <input type="text"> <h1>Result</h1> </div> <script src="script.js"></script> </body> </html>
.container { display: flex; flex-direction: column; justify-content: space-between; align-items: center; height: 70px; }
Javascript
- We have selected the
h1
element using thedocument.querySelector()
method and stored it in theresult
variable. - We have attached the
keyup
event listener to thewindow
. - In the event handler function, we are using the
key
property of the event object to get the key pressed by the user and setting it asinnerText
of theh1
element.
let result = document.querySelector('h1'); window.addEventListener('keyup', (e) => { result.innerText = e.key; });