jQuery event.which Property

jQuery event.which property returns the number of which keyboard key or mouse button was pressed.

The event.which property alternative you can use keyboard event.keyCode and event.charCode event.

The event.which property return on mouse button presses respectively 1 for left button, 2 for middle, and 3 for right.

Syntax

event.which
Parameter Type Description
event Event Required. The event parameter comes from event bind method

Examples

This example returns the key code of pressed keyboard key.

<!DOCTYPE html>
<html>
<head>
  <title>jQuery event.which property</title>
  <script src="jquery-latest.min.js"></script>
  <script>
    $(document).ready(function(){
      $("input").keydown(function(event){ 
        $("span").text("Pressed Key: " + event.which);
      });
    });
  </script>
</head>
<body>
    <p>Press any keyboard key on below input</p>
    <input type="text" name="keyboard">
    <br /><br />
    <span></span>
</body> 
</html>

Run it...   »


This example returns the key code of pressed keyboard key.

<!DOCTYPE html>
<html>
<head>
  <title>jQuery event.which property (for mouse button)</title>
  <script src="jquery-latest.min.js"></script>
  <script>
    $(document).ready(function(){
      $("div").mousedown(function(event){ 
        $("span").append("Mouse button Pressed: " + event.which + "<br />");
      });
    });
  </script>
  <style>
    div {
      width: 400px;
      height: 200px;
      border: 1px solid black;
    }
  </style>
</head>
<body>
    <p>Mouse button click on below div element.</p>
    <div>
      <span></span>
    </div>
</body> 
</html>

Run it...   »