With jQuery, how do I find out which key was pressed when I bind to the keypress event?
$(\'#searchbox input\').bind(\'keypress\', function(e) {});
>
event.key
and modern JS!No number codes anymore. You can check key directly. For example "Enter"
, "LeftArrow"
, "r"
, or "R"
.
const input = document.getElementById("searchbox");
input.addEventListener("keypress", function onEvent(event) {
if (event.key === "Enter") {
// Submit
}
else if (event.key === "Q") {
// Play quacking duck sound, maybe...
}
});
Mozilla Docs
Supported Browsers