jQuery | event.which property with Examples

The event.which is an inbuilt property in jQuery which is used to return which keyboard key or mouse button was pressed for the event.
Syntax:

event.which

Parameter: It does not accept any parameter because it is a property not a function.
Return Value: It returns which keyboard key or mouse button was pressed.

jQuery code to show the working of this property:

Code #1:
In the below code, ascii value of the key is displayed.



filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
  
<head>
    </script>
    <script>
        $(document).ready(function() {
            <!-- jQuery code to show event.which property -->
            $("input").keydown(function(event) {
                $("div").html("Key: " + event.which);
            });
        });
    </script>
    <style>
        div {
            margin: 20px;
            width: 80px;
            height: 60px;
            padding: 20px;
            border: 2px solid green;
        }
    </style>
</head>
  
<body>
    <!-- Here ascii value of the key will be shown -->
    <div>
        <p></p>
    </div>
    Name :
    <input type="text">
</body>
  
</html>

chevron_right


Output:
Ascii value of “G” is shown-

Code #2:
In the below code, which mouse button was pressed is displayed.

filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
  
<head>
    <script 
    </script>
    <script>
        <!-- jQuery code to show event.which property -->
        $(document).ready(function() {
            $("div").mousedown(function(event) {
                $("div").append("<br>Mouse button : " + event.which);
            });
        });
    </script>
    <style>
        div {
            border: 2px solid green;
            width: 400px;
            height: 300px;
            padding: 20px;
        }
    </style>
</head>
  
<body>
    <!-- click inside and see -->
    <div style="">Click anywhere in this box !!!</div>
</body>
  
</html>

chevron_right


Output:
When left button of mouse is clicked:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.