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

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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

 

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Published at DZone with permission of Stoimen Popov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}