Which keycode for escape key with jQuery

Learn about the keycode for escape key and how to detect it when pressed on the keyboard using jQuery?
Submitted by Pratishtha Saxena, on December 23, 2022

We can detect the keys from the keyboard using the unique KeyCode that each key holds. When we talk about the 'ESC' key, its unique key code is '27'. This code has to be known before you.

Syntax:

event.keyCode == 27

Hence, by declaring a function along with the keypress events, we can execute actions based on the detection of the ESC key when pressed. This can be seen in the example given below.

Example 1

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>Which keycode for escape key with jQuery</h2>
    <p>Enter name & press escape key from the keyboard and see the result.</p>
    <hr>
    <br>
    Enter Name : <input type="text" value="" placeholder="Press ESC Once Finished">
    <h4></h4>
    <hr>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('input').keydown(function(event){
            if (event.keyCode == 27) {
                $('h4').html('Hey ' + $('input').val());
            }
        });
    })    
  </script>
</html>

Output:

Example 1: Which keycode for escape key with jQuery

If one does not know the exact key code of the ESC key, then, in that case, the name 'Escape' can also be considered. We can specify the key name as Escape and when the key is pressed, the condition can be checked. If the key pressed is the ESC key, then further actions are executed. This is shown in the example given below.

Example 2

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>Which keycode for escape key with jQuery</h2>
    <p>Enter name & press escape key from the keyboard and see the result.</p>
    <hr>
    <br>
    Enter Name : <input type="text" value="" placeholder="Press ESC Once Finished">
    <h4></h4>
    <hr>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('input').keydown(function(event){
            if (event.key == 'Escape') {
                $('h4').html('Hey ' + $('input').val());
            }
        });
    })   
  </script>
</html>

Output:

Example 2: Which keycode for escape key with jQuery




All jQuery Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.