Determine If multiple keys are pressed at once using JavaScript

Hello, Everyone Today we will determine or Find out and add an Event listener that detects if two keys are pressed at once.

It is common for developers to create shortcuts for users if they press some key combinations then something happens for example we see in Windows or Mac shortcuts to copy-paste are given like in Windows the shortcut for copy is ctrl + c etc

Today we will be creating a function that gonna listen and responds only when two keys are pressed.

Let's begin:

The Plan (Theory): 


Firstly we gonna think about how we can achieve it using JavaScript. We got key event listeners like key down and key up.


KeyDown: This will detect a key only when the key is pressed.


keyUp: This will detect a key only when the key is released.


So we will leverage the above methods to resolve our problem. Firstly we gonna create an object {

key1: false,

key2: false

}


like the above and assigned the object the properties here the two keys which we are detecting at once give the properties the value of a Boolean false.



This means our keys are off.



Now we will add the event listener keyDown and add the conditions to detect a key using the event object of the listener. 


For example if event.key === "w" then object.key1 = true 

if event.key === "a" then object.key1 = true


Now we stored both of the results in our object keys. Now we need the last condition to check whether both of the object properties return true if it's true then we know that both the keys are pressed.



Now you will be thinking what's the use of the keyup event listener or the key release listener.



it is important because we need to determine when the key is released so we need to use it and add conditions to it like for example



if event.key === "w" then make our object key value false do this two times for both the keys.



Now our problem is resolved we are now able to detect multiple keys at once using JavaScript.

Executing the plan (The Practical Coding Part):


Creating The Object with the properties of the keyboard keys we want to detect and giving both of them false boolean value as both the keys are not pressed.



let keys = {
  a: false,
  s: false,
};



addEventListener("keydown", (event) => {

  if (event.key === "a") {
    keys.a = true;
  }
  if (event.key === "s") {
    keys.s = true;
  }

if(keys.a && keys.s){
  console.log("both the keys pressed at once")
}

});


Like in the above plan I have mentioned throwing condition to find which key is pressed using the event object of the listener.

Here in the above code, we are determining separately if our desired key is pressed. In this example, our desired key is a and s. If our desired keys are pressed then we need to change our object that we created above and change its property to true.

After this, we need to add the third condition to determine if both of the properties of our object is true if it's true then we know that both the keys are pressed at once by the user. 

Last thing we need to also find out when the keys are released by the user if we don't do this then our object properties remain true all the time and cause undesirable results.

addEventListener("keyup", (event) => {
  if (event.key === "a") {
    keys.a = false;
  }
  if (event.key === "s") {
    keys.s = false;
  }
});

 In the above code, we are resetting our object properties when the user released the keys after pressing them.


Finally, we completed and if you follow along with me you understood the concept and how this works and now you can try by your self for three keys pressed at once. 


Final Code: 

    let keys = {
      a: false,
      s: false,
    };

    addEventListener("keydown", (event) => {
      if (event.key === "a") {
        keys.a = true;
      }
      if (event.key === "s") {
        keys.s = true;
      }

    if(keys.a && keys.s){
      console.log("both the keys pressed at once")
    }

    });

    addEventListener("keyup", (event) => {
      if (event.key === "a") {
        keys.a = false;
      }
      if (event.key === "s") {
        keys.s = false;
      }
    });


Conclusion: 

I wrote this article to make sure my readers understand the code and how it works instead of just getting the code and using it in the application. if you understand then you can customize and add more functionality to it.

No comments:

Post a comment