Creating Keyboard Shortcuts in JavaScript

Creating Keyboard Shortcuts in JavaScript
Code Snippet:Custom Keyboard Shortcut using JavaScript
Author: Reema
Published: January 20, 2024
Last Updated: January 22, 2024
Downloads: 552
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code allows you to create a custom keyboard shortcut (a + b) in your web application. When both keys are pressed simultaneously, a specific action is triggered. It helps you enhance user experience by enabling easy navigation or execution of functions.

Yes, you can define your own custom keyboard shortcuts using this code. Simply modify the isKeyPressed object to include the keys you want in your custom shortcut, and adjust the logic inside the document.onkeydown event handler to check for your desired key combination. Moreover, this code provides a framework for creating and handling custom keyboard shortcuts in JavaScript.

How to Create Creating Keyboard Shortcuts In Javascript

1. First, create the HTML structure for your shortcut interface. The following code includes a container with two text sections to display messages when the shortcut is clicked and when it’s not. (Optional you can use your own)

<div class="container">
  <div class="shortcut-not-clicked-text">
    <p>No Keyboard Shortcut is Clicked</p>
    <p class="small-text">[click a + b to trigger the global shortcut]</p>
  </div>
  <div class="shortcut-clicked-text"><p> a + b shortcut is clicked</p>
  </div>
</div>

2. Utilize CSS to style the interface and make it visually appealing. The code includes media queries for responsiveness on different devices. (Optional)

/* Media Queries */

/* Small Devices*/

@media (min-width: 0px) {
  
* {
  box-sizing: border-box;
}

  
  body {
    margin: 0;
    padding: 0;
  }

  .container {
    background-color: lightpink;
    height: 100vh;
    width: 100%;
    /*targeting Chrome & Safari*/
    display: -webkit-flex;
    /*targeting IE10*/
    display: -ms-flex;
    display: flex;
    justify-content: center;
    /*vertical centering*/
    align-items: center;
    /*horizontal centering*/
    flex-direction: column;
    padding: 0 10px 0 10px;
  }

  .shortcut-not-clicked-text,
  .shortcut-clicked-text {
    font-size: 30px;
    width: 100%;
    text-align: center;
    font-family: monospace;
    /*targeting Chrome & Safari*/
    display: -webkit-flex;
    /*targeting IE10*/
    display: -ms-flex;
    display: flex;
    justify-content: center;
    /*vertical centering*/
    align-items: center;
    /*horizontal centering*/
    flex-direction: column;
    margin: 0;
    padding: 0;
  }

  .small-text {
    font-size: 20px;
  }

  .shortcut-clicked-text {
    display: none;
  }
}

/* Medium devices */

@media (min-width: 768px) {
  .shortcut-not-clicked-text,
  .shortcut-clicked-text {
    font-size: 70px;
  }

  .small-text {
    font-size: 30px;
  }
}

/* Large devices */

/* @media (min-width: 992px) {} */

/*Ipad pro view*/

/* 
@media (min-width: 1024px) {

} */

/* Extra Large devices */

/* @media (min-width: 1200px) {} */

3. To create your own shortcut, modify the isKeyPressed object and adjust the logic inside the document.onkeydown event handler. You can customize the actions that you want to run.

/*Note that the use of the keyCode attribute on the key event should be 
avoided as MDN considers it a deprecated attribute. Therefore, the key 
attribute is used instead.*/

const shortcutNotClickedTextRef = document.getElementsByClassName(
  "shortcut-not-clicked-text"
)[0];
const shortcutClickedTextRef = document.getElementsByClassName(
  "shortcut-clicked-text"
)[0];

// Keep track of clicked keys
var isKeyPressed = {
  a: false, // ASCII code for 'a'
  b: false // ASCII code for 'b'
  // ... Other keys to check for custom key combinations
};

document.onkeydown = keyDownEvent => {
  //Prevent default key actions, if desired
  keyDownEvent.preventDefault();

  // Track down key click
  isKeyPressed[keyDownEvent.key] = true;

  // Check described custom shortcut
  if (isKeyPressed["a"] && isKeyPressed["b"]) {
    //for example we want to check if a and b are clicked at the same time
    //do something as custom shortcut (a & b) is clicked

    // show text indicating shortcut is clicked
    shortcutClickedTextRef.style.display = "flex";
    shortcutNotClickedTextRef.style.display = "none";
  }
};

document.onkeyup = keyUpEvent => {
  // Prevent default key actions, if desired
  keyUpEvent.preventDefault();

  // Track down key release
  isKeyPressed[keyUpEvent.key] = false;

  // when one of the keys is released, show text indicating
  // text is no longer clicked
  if (!isKeyPressed["a"] || !isKeyPressed["b"]) {
    shortcutClickedTextRef.style.display = "none";
    shortcutNotClickedTextRef.style.display = "flex";
  }
};

That’s all! hopefully, you have successfully created Creating Keyboard Shortcuts In Javascript. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X