简体   繁体   中英

how to detect when a shortcut key is pressed in javascript

How can i detect a shortcut key, [ in my case [ ctrl + shift + k ] ] in javascript? Like, i have to show a dialog if user presses this key.

document.onkeydown = keydown;

function keydown(evt){
  if (!evt) evt = event;
  if (evt.ctrlKey && evt.altKey && evt.keyCode==115){ //CTRL+ALT+F4
    alert("CTRL+ALT+F4"); 
  }
  else if (evt.shiftKey && evt.keyCode == 9){ //Shif+TAB
    alert("Shift+TAB");
  }
}

Ontop of the url Dominic posted will give you the key codes.

Knowing that this is a very old issue (13 years before)
but I share my best answer in 2022,if I shared it 13 years ago I guess it would have been marked as solution
so this answer is based on code boxx

HTML

<!-- FOR THE DEMO -->
<div id="demoA"></div>

Javascript

var shortcut = {
  // (A) SET SHORTCUT KEYS TO LISTEN TO
  listen : null,
  set : (listen) => {
    // (A1) KEY SEQUENCE + FUNCTION TO RUN
    shortcut.listen = listen;

    // (A2) KEY PRESS LISTENERS
    window.addEventListener("keydown", (evt) => {
      shortcut.track(evt.key.toLowerCase(), true);
    });
    window.addEventListener("keyup", (evt) => {
      shortcut.track(evt.key.toLowerCase(), false);
    });
  },

  // (B) KEY PRESS SEQUENCE TRACKER
  sequence : [],
  track : (key, direction) => {
    // (B1) PREVENT AUTO CLEANING
    if (shortcut.junk != null) { clearTimeout(shortcut.junk); }

    // (B2) KEY DOWN
    if (direction) { if (!shortcut.sequence.includes(key)) {
      shortcut.sequence.push(key);
    }}

    // (B3) KEY UP
    else {
      let idx = shortcut.sequence.indexOf(key);
      if (idx != -1) { shortcut.sequence.splice(idx, 1); }
    }

    // (B4) HIT SHORTCUT?
    if (shortcut.sequence.length != 0) {
      let seq = shortcut.sequence.join("-");
      if (shortcut.listen[seq]) {
        shortcut.sequence = [];
        shortcut.listen[seq]();
      }

      // (B5) PREVENT "STUCK SEQUENCE" WHEN USER LEAVES PAGE
      // E.G. OPEN NEW TAB WHILE IN MIDDLE OF KEY PRESS SEQUENCE
      else {
        shortcut.junk = setTimeout(shortcut.clean, 600)
      }
    }
  },

  // (C) AUTO CLEANUP
  junk : null,
  clean : () => {
    shortcut.junk = null;
    shortcut.sequence = [];
  }
};
window.addEventListener("DOMContentLoaded", () => {
  shortcut.set({
    "control-shift-k" : () => {// Use https://keycode.info/ to help you get the key name [*]
       document.getElementById("demoA").innerHTML = "CONTROL SHIFT K IS PRESSED"//[*]
       document.getElementById("demoA").style.color = "green";//[*]
       document.getElementById("demoA").style.backgroundColor = "lightgreen";//[*]
      }
  });
});

document.onkeydown = function (e) {//remove this function if you dont want to block default action
  // normalize event
  e = e || window.event;

  // detecting multiple keys, e.g: Ctrl + shift + k and block default action (in edge it duplicates tab)
  if (e.ctrlKey && !e.altKey && e.shiftKey && e.keyCode === 75) {//75 means k [*]
    // prevent default action
    if (e.preventDefault) {
      e.preventDefault();
    }
    // IE
    e.returnValue = false;
  }
};

//[*] represents you have to change the code line for your needs

Features

  • Shortcuts in SEQUENCE
  • Block default shortcut like duplicate tab in edge for ctrl+shift+k (might remove if you don't wan't to do so
  • Full of comments

Here is a demo website(click open in new window live)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM