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.
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: 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: 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();
});