event.whichReturns: Number
Description: For key or mouse events, this property indicates the specific key or button that was pressed.
version added: 1.1.3event.which
The event.which
property normalizes event.keyCode
and event.charCode
. It is recommended to watch event.which
for keyboard key input. For more detail, read about event.charCode on the MDN.
event.which
also normalizes button presses (mousedown
and mouseup
events), reporting 1
for left button, 2
for middle, and 3
for right. Use event.which
instead of event.button
.
Examples:
Log which key was depressed.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.which demo</title>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<input id="whichkey" value="type something">
<div id="log"></div>
<script>
$( "#whichkey" ).on( "keydown", function( event ) {
$( "#log" ).html( event.type + ": " + event.which );
});
</script>
</body>
</html>
Demo:
Log which mouse button was depressed.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.which demo</title>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<input id="whichkey" value="click here">
<div id="log"></div>
<script>
$( "#whichkey" ).on( "mousedown", function( event ) {
$( "#log" ).html( event.type + ": " + event.which );
});
</script>
</body>
</html>