Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading