Make Keyboard ShortCut in Javascript

kiumad

Mohammad Mirfatemi

Posted on July 5, 2022

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
💖 💪 🙅 🚩
kiumad
Mohammad Mirfatemi

Posted on July 5, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related