34

Find KeyCode in JavaScript - Core JavaScript

 5 years ago
source link: https://www.tuicool.com/articles/hit/YbMNnye
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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){
    console.log(e.keyCode);
  });

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;
alert(result);
});

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">
<head>
  <meta charset="UTF-8">
  <title>Find the keycode in JavaScript</title>
</head>
<body>
<script>
  window.addEventListener('keydown', function(e){
var result=e.keyCode;
alert(result);
});
</script>
</body>
</html>

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

Also read,


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK