Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Detecting Pressed Key with e.which in JavaScript

DZone's Guide to

Detecting Pressed Key with e.which in JavaScript

· Web Dev Zone ·
Free Resource

Bugsnag monitors application stability, so you can make data-driven decisions on whether you should be building new features, or fixing bugs. Learn more.

You have definitely decided to get which key has been pressed with JavaScript? This is very common when it comes to an Enter key press over a form element. Actually this should be automatically done by the browser, but when it comes to a default prevented form you’ve to check it for yourself.

The job can be done with a event’s which check. Let me show you some JavaScript/jQuery code:

$('.selector').click(function(e) {
console.log(e.which);
});

Note that this can be checked under Firefox and/or Safari like browsers which support the console object. This will give you the idea which key is pressed in a number value. The Enter is usually 13!
If you don’t have such browser, you can replace that code with something like:

$('.selector').click(function(e) {
alert(e.which);
});

 

Monitor application stability with Bugsnag to decide if your engineering team should be building new features on your roadmap or fixing bugs to stabilize your application.Try it free.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}