Saturday, 25 August 2018

Detect The Keyboard Key Clicks In JavaScript

Well, you might have seen on the different websites and web apps that you can control them on keyboard.For example, you can hit spacebar for play/pause the video or F to toggle full-screen. You can apply it to your project too. For that, you need to detect the keyboard clicks in JavaScript.

How to detect keyboard clicks in JavaScript?

For that, we need to write a little JS code. Have a look at that.
document.onkeydown = keyCtrl;//will map all the keyboard actions.
function keyCtrl(e) { 
    if (e.keyCode == '67') {
        // Add function code here
Okay, here we have made a function that will detect the key actions. For that, we need to know the keyCode of that particular key.In above code, it is 67 means 'C'.You can take a look at below chart or simply go to keycode and hit the key of which you want to find the keyCode.
JavaScript character codes key codes.

So that's it!
Below is an example of a function that will alert once the caps lock key is pressed.
If you want demo then try clicking caps-lock:).
document.onkeydown = keyCtrl;
function keyCtrl(e) { 
    if (e.keyCode == '20'){
        alert("You Just pressed Caps-Lock!");}}

Solution To Some Known Issues

What do I do to block the default function when I click on the function keys?
In this case you can use  event.preventDefault() to prevent the default functions.

That's it for this post, hope you like it and Do check other posts.

0 Please Share a Your Opinion.:

Comment something useful and creative :)