Search code examples
javascriptdom-eventskeyboard-eventsuserscripts

how to detect a Key Sequence in Javascript


i am writing an userscript that post in a forum each time a shortcut sequence is executed [ ctrl + enter ], but the function that i wrote excecutes both keydowns as separate events, and not a single sequence.

i checked the related questions, but none of them really exlained how to configure the function to handle the sequence.

this is the code that i wrote :

let boutton_toast = document.querySelector('.btn-poster-msg');

function toast(e){
    if (e.ctrlKey && e.key=="Enter"){
       boutton_toast.click();
    }
}
document.addEventListener("keydown", toast)

i feel like the answer is really obvious but i can't guess it.

edit :

i used fordat's method and it worked, here's the final code :

let button_toast = document.querySelector('.btn-poster-msg');
        let pressedKeys = [];

        function bothKeysPressed() {
            if (pressedKeys.includes('Enter') && pressedKeys.includes('Control')) {
                button_toast.click();
            }
        }

        document.addEventListener('keydown', () => {
            pressedKeys.push(event.key)
            bothKeysPressed();
        })

        document.addEventListener('keyup', () => {
            pressedKeys = pressedKeys.filter(key => key !== event.key)
        })


Solution

  • You could try creating a list (or any data structure really) that stores the variables, something like this:

    pressedKeys = [];
    
    function bothKeysPressed() {
        if (pressedKeys.includes('Enter') && pressedKeys.includes('Control')) {
          console.log("Enter and Control are pressed!");
        }
    }
    
    document.addEventListener('keydown', () => {
       pressedKeys.push(event.key)
       bothKeysPressed();
    })
    
    document.addEventListener('keyup', () => {
       pressedKeys = pressedKeys.filter(key => key !== event.key)
    })
    

    Then just include an additional function in your "keydown" listener that checks for the two keys you need.