DEV Community

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

Posted on

3 2

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)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Dive into this insightful write-up, celebrated within the collaborative DEV Community. Developers at any stage are invited to contribute and elevate our shared skills.

A simple "thank you" can boost someone’s spirits—leave your kudos in the comments!

On DEV, exchanging ideas fuels progress and deepens our connections. If this post helped you, a brief note of thanks goes a long way.

Okay