How to find the Keycode in JavaScript ( Core JavaScript no jQuery )

Hello, in this post I am going to show you how to find keycode in JavaScript. I will create a JavaScript function that will print the keycode of the pressed key.

I will show you by printing the keyCode in the console log. But you can use this code to print it wherever you want. Like in a div area or in the alert message, wherever you want. You can easily do this with jQuery, But here I am gonna use only pure or core JavaScript. No jQuery at all.
Press any key on this page to find it’s key code now

You can get a better idea on what I am going to do if you read How To Detect Keypress In Javascript

Find keyCode in JavaScript Easily

window.addEventListener('keydown', function(e){

Here addEventListener() method is used. In this method, we can use two parameters. The first one is: for which event and the second one is for: what to do. That means a function, where we mention what to do by the line of codes.

keydown is an event and browser gonna listen for this event in the above example. The function will then print the event’s keycode.

Detect if particular word typed in textarea in JavaScript

you can also use

window.addEventListener('keydown', function(e){
var result=e.keyCode;

If you run this code and press any key ( actually, most of the key ) on the browser, it will alert the keycode of the corresponding key.

Here is a full example.

<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  <title>Find the keycode in JavaScript</title>
  window.addEventListener('keydown', function(e){
var result=e.keyCode;

Finally, Feel free to comment below. We will be happy to hear from you if have any doubt or question.

Also read,

Detect arrow key press in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *