How to Detect Escape Key Press with Javascript

In this tutorial, you will learn how to detect escape key press with javascript. In a standard keyboard layout, the Esc key is located on the top-left corner. It is also known as escape key and is generally used to stop an active process or close a window.

Whenever we press a key on the keyboard, certain keyboard events are triggered. In the event handler function, the event object contains details about the keyboard event. The event object has a key property that can reveal which key has been pressed by the user.

To keep things simple, we are going to monitor keyup event and in the event handler function, we will verify whether the escape key is pressed or not.

In the following example, we have an input element.  As soon as the user presses the escape key while typing in the input field, we will display a message on the screen. Please have a look over the code example and the steps given below.


  • We have 3 elements in the HTML file (div, h1, and input).
  • The div element is just a wrapper for the rest of the elements. We are using style attribute with div element to center align the child elements.
  • The innerText for the h1 element is “Result”.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <div style="text-align: center">
        <input type="text" placeholder="Enter Text">
    <script src="script.js"></script>


  • We have selected the input element and h1 element using document.querySelector() method and stored them in the input and result variables respectively.
  • We have attached keyup event listener to the input element.
  • In the event handler function, we are using if statement and key property of the event object to verify whether the escape key is pressed or not.
  • Depending upon the result of verification, we are updating innerText of the h1 element.
let input = document.querySelector("input");
let result = document.querySelector("h1");

input.addEventListener("keyup", (e) => {
  if (e.key === "Escape") {
    result.innerText = "Escape Key Pressed";
  } else {
    result.innerText = "Escape Key Not Pressed";