Search code examples
javascriptkeyboard-shortcutshotkeys

JavaScript: implement sequential keyboard hotkey?


For example, I want to implement something like do action when you typed sequentially shift-s then s, in JavaScript. I'm inspired by Autohokey, hotkey configuration software/language for Windows, so I'm looking for a library or way to implement something that in JS.

So far I found a library called hotkeys, but I have no idea to implement a sequential keyboard hotkey and didn't find any issue or question about it also, so here I am. So, how can I implement that in JS using the library or other library? Thanks.


Solution

  • This can be done easy with keydown event listener, no library needed for this

    sAgain = false
    
    document.addEventListener('keydown', function(event) {
      if (sAgain && event.key.toLowerCase() == 's')
        alert("shift-s then s clicked")
      else if (event.shiftKey && event.key.toLowerCase() == 's')
        sAgain = true
      else
        sAgain = false //stop listen if other key is clicked after shift-s
    });
    <h1>Press shift s then s<h1>