DEV Community 👩‍💻👨‍💻

Cover image for Make Keyboard ShortCut in Javascript
Mohammad Mirfatemi
Mohammad Mirfatemi

Posted on

Make Keyboard ShortCut in Javascript

Creating a shortcut in javascript with 5 lines of code!
To create a shortcut, we must first listen to the pressing of the keyboard keys on the document
Then specify the keys we want to simplify with an if
Finally, we have to eliminate the normal behavior of that shirt with preventDefault

// Listen to keydown event on the document
document.addEventListener("keydown", (e) => {
  if (e.key.toLowerCase() === "s" && e.ctrlKey) {
    // disable the default behavior of the ctrl + s
    e.preventDefault();
    // your code here
    alert("S key pressed with ctrl");
  }
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.