15

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.

1

2 Answers 2

21
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.

3
  • 1
    var evt=(evt)?evt:(window.event)?window.event:null; - i would add this for initiating event.
    – Trick
    Nov 13, 2009 at 8:43
  • 1
    How does this keep the sequence? Mar 8, 2021 at 13:17
  • Note that KeyboardEvent.keyCode is deprecated and you should now use KeyboardEvent.code instead (reference: MDN).
    – Karel
    Jan 29 at 13:43
6

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)

1
  • 1
    This answer deserves an upvote. Cheers. Mar 4, 2022 at 12:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.