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

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

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);
});

 

Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.

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 }}