How can I detect pressing Enter on the keyboard using jQuery?

Learn, how to detect pressing of Enter key on keyboard using jQuery?
Submitted by Pratishtha Saxena, on August 30, 2022

prerequisite: Adding jQuery to Your Web Pages

Sometimes, it is necessary to figure out how and know when which key is pressed by the user on the keyboard so that some other events are queued accordingly.

Therefore, jQuery provides a keypress() method for the same. This method helps to trigger an event or some function that is attached to it when any key is pressed. There are similar methods like keypress() - keyup(), keydown(), etc. whose functions can be easily assumed.

Syntax:

$('selector').keypress(function(event))

Hence when any key is pressed the function gets triggered. Now, to find whether the key pressed is the ENTER key, we need to specify the ASCII value of the enter key which is 13. To achieve this, this condition is specified within the function. If the key pressed is ENTER, i.e., the value of the key pressed is 13 then further implementation of the function will go on.

Let's get into an example of this.

Example to detect pressing Enter on the keyboard using jQuery

<!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>
	
    <style type="text/css">
      .box{
      border: 5px solid rgb(32, 125, 218);
      background-color: rgb(0, 0, 0);
      height: 100px;
      width: 200px;
      }
      .para{
      font-size: large;
      color: rgb(3, 30, 164);
      font-weight: bolder;
      font-style: italic;
      }
      .heading{
      color:crimson;
      font-style: oblique;
      }
    </style>
	
  </head>
  
  <body>
    <h2>Detect Pressing ENTER Key on Keyboard Using jQuery.</h2>
    <p>Write 'APPLY CSS' in the following text box and hit ENTER to see the result.</p>
    <label>Write Here: </label>
    <input type="text" id="myText">
    <br><br>
    <div></div>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
            $('#myText').on("keypress",function(event){
                if (event.which == 13){
                    $('h2').addClass('heading');
                    $('p').addClass('para');
                    $('div').addClass('box');
                }
            })
        });      
  </script>
</html>

Output:

Example 1: Detect pressing Enter on the keyboard using jQuery

Example 2: Detect pressing Enter on the keyboard using jQuery





Comments and Discussions!

Load comments ↻





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