By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > How to Work With Responding to and Tracking Key Presses
JavaScript

How to Work With Responding to and Tracking Key Presses

Admin
Last updated: 2023/02/05 at 6:22 AM
Admin
Share
4 Min Read
Responding to and Tracking Key Presses

In this article, we are going to see about JavaScript Problem: Responding to and Tracking Key Presses. We are going to look at adding a handler to capture and respond to keyboard events. We will capture those key presses and then display them. So this is going to be a very easy practice and this article will explain you in very simple manner.

Contents
Responding to and Tracking Key Presses: Simple MethodResponding to and Tracking Key Presses: Capture and StoreResponding to and Tracking Key Presses: Modification in Key PressesYou may also like:

So let see a very basic example with which we can track the key presses using event listener.

Responding to and Tracking Key Presses: Simple Method

As you can see in the below example, we have created a simple function in which we have added an event listener on the whole page to listen a pressed key using keydown event. Here we have added a variable to get key value using e.key and we are consoling this in the console. A very simple and straight-forward program.


        var keyCapture = function (){
            document.addEventListener("keydown", (e)=>{
                let key = e.key;
                console.log(key);
            });
        };

        document.addEventListener("DOMContentLoaded", (e)=>{
            keyCapture();
        });
 
Responding to and Tracking Key Presses

Responding to and Tracking Key Presses: Capture and Store

So now lets move further to capture and store these key presses into some sort of array. We have the same code as above, but here we have some modification. Here we have added an array, and again we added event listener to listen “keydown”, and we have store e.key in the variable. Also, we will check if key is equal to “Enter” then we will console this array, else we will push the pressed key in this array.

So basically, we will press some keys and if we hit enter, then we will get an array of the previous keydown values.


        var keyCapture = function (){
            let keySeries = [];
            document.addEventListener("keydown", (e)=>{
                let key = e.key;
                if(key === "Enter"){
                    console.log(keySeries);
                    keySeries = [];
                }else{
                    keySeries.push(key);
                }
            });
        };

        document.addEventListener("DOMContentLoaded", (e)=>{
            keyCapture();
        });
Responding to and Tracking Key Presses

Responding to and Tracking Key Presses: Modification in Key Presses

As we have done in the above example, we are able to capture every kind of key like ‘Alt’,’Shift’ etc. Now we will do some modification, so we can only get alphabets and number as output. For that, we have added a simple regular expression, which contains only alphabets and number. We have to apply check() method on keys, and we have converted these key in lowercase, so we can compare with regular expression.

By doing this, if we try to put some key except alphabets and numbers, then those keys won’t we added in the keySeries array, since we will compare keys with the regular expression.


        var keyCapture = function (){
            let keySeries = [];
            const validKeys = /^[abcdefghijklmnopqrstuvwxyz0123456789]$/;
            document.addEventListener("keydown", (e)=>{
                let key = e.key;
                if(key === "Enter"){
                    console.log(keySeries);
                    keySeries = [];
                }else if(validKeys.test(key.toLocaleLowerCase())){
                    keySeries.push(key);
                }
            });
        };

        document.addEventListener("DOMContentLoaded", (e)=>{
            keyCapture();
        });
Responding to and Tracking Key Presses

You may also like:

  • How to Define a Class With Properties and Methods in JavaScript?
  • How to Implement Class Inheritance in JavaScript?
  • How to Find Duplicate Elements in a Given Array?

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

TAGGED: javascript, Responding to and Tracking Key Presses
Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Posted by Admin
Follow:
Rocoderes is a blog you can learn HTML, CSS, JavaScript, React Js and Python along with creative coding stuff and free source code files.
Previous Article Passing a JavaScript Value Between HTML Pages Passing a JavaScript Value Between HTML Pages
Next Article How to close dropdown by clicking outside? Javascript – How to close dropdown by clicking outside?
Leave a comment Leave a comment

Leave a Reply Cancel reply

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

- Advertisement -

You Might Also Like

How to set the dropdown value by clicking on a table row

Javascript – How to set the dropdown value by clicking on a table row

February 11, 2024
Attempting to increase the counter, when the object's tag exist

Javascript – Attempting to increase the counter, when the object’s tag exist

February 11, 2024
Cycle2 JS center active slide

Javascript – Cycle2 JS center active slide

February 10, 2024
Can import all THREE.js post processing modules as ES6 modules except OutputPass

Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass

February 10, 2024
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?