skip to Main Content
function Press(){
    document.querySelector("body").addEventListener("keyup", event => {
        if(event.key !== "Shift") return;
        document.getElementById("myElement").click();
        event.preventDefault();
    });
}

I set keyup for press Shift 1 time. How can I set it for 3 fast times? So that after Shift Shift Shift an event (document.getElementById("myElement").click()) is executed?

UPDATE:

this is working code made with @deceze help

function Press(){
    document.addEventListener("keyup", event => {
        if(event.key !== "Shift") return;
        shift_pressed = typeof shift_pressed !== 'undefined' ?  shift_pressed : 0;
        shift_pressed++;
        setTimeout(() => {
            shift_pressed= shift_pressed-1 >= 0 ? shift_pressed-1 : 0;
        }, 1000);
        if (shift_pressed===3){
            document.getElementById("myElement").click();
            shift_pressed=0;
        }
        event.preventDefault();
    });
}

thanks everyone for the help

2

Answers


  1. That should trigger the click on every third press of the Shift key

            function Press(){
                const THRESHOLD = 250;
                let counter = 0;
                let millis = Date.now();
                document.querySelector("body").addEventListener("keyup", event => {
                    if(event.key !== "Shift") return;
                    if(Date.now()-millis > THRESHOLD) counter = 0;
                    if(++counter%3===0) { 
                     document.getElementById("myElement").click();
                     event.preventDefault();
                    }
                    millis = Date.now();
                });
            }
    
    Login or Signup to reply.
  2. Just create setTimeout for clearing counter of clicking Shift and define clearTimeout clear the timeout for every single click.

    document.getElementById("myElement").onclick = () => {
      console.log('Hello World!');
    }
    
    let clearTime = 1000;
    let counterShift = 0;
    let timeout;
    document.querySelector("body").addEventListener("keyup", event => {
        if(event.key !== "Shift") return;
        clearTimeout(timeout);
        counterShift++;
        console.log('number click:',counterShift);
        if(counterShift == 3) {
          document.getElementById("myElement").click();
          event.preventDefault();
          counterShift = 0;
        }
        timeout = setTimeout(()=>{
          counterShift = 0;
        }, clearTime);
    });
    <button id="myElement">Test</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search