skip to Main Content

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.

2

Answers


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

    Login or Signup to reply.
  2. I’m not sure I follow.

    this certainly works:

    let div = document.querySelector('.test');
    let counter = document.querySelector('#counter');
    var i=0;
    function toast(e){      
        if (!e.repeat && e.ctrlKey && e.key=="Enter"){ // check for e.repeat otherwise if user holds down both keys it calls the function repeatedly 
            //console.log(e)
            let randomColor = '#' + Math.floor(Math.random()*16777215).toString(16);        
            div.style.backgroundColor=randomColor;
            i+=1;
            counter.innerText=i;
        }
    }
    document.addEventListener("keydown", toast);
    <div style="width: 10em; height: 4em; background-color: lightblue" class="test"></div>
    <div id="counter">0<div>

    You’re missing a closing "}" in your attached code.

    Please attach a minimal reproducible example.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search