Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to detect when a shortcut key is pressed in javascript

Tags:

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.

like image 967
Rakesh Juyal Avatar asked Nov 13 '09 08:11

Rakesh Juyal


People also ask

How do you check if a certain key is pressed in JavaScript?

Detecting keys in JavaScriptdocument. onkeydown = function (e) { console. log('key down'); console. log(e); };

What is e keyCode === 13?

Keycode 13 is the Enter key.

When Ctrl T is pressed what appears?

Ctrl+T in an Internet browser In all major Internet browsers (e.g., Chrome, Edge, Firefox, IE, Opera), pressing Ctrl + T opens a new tab.


2 Answers

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)

like image 85
Neptotech -vishnu Avatar answered Nov 12 '22 17:11

Neptotech -vishnu


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.

like image 23
medoix Avatar answered Nov 12 '22 16:11

medoix