0

I'm trying to come up with a solution to press keys virtually for a typing test. What I want is to get the text and store individual letters in an array and then press all keys with some delay in between each presses.

This is the HTML of the text layout. Imagine it has the word hello.

<div class="digit-container">
    <div>
        <span>h</span>
    </div>
</div>
<div class="digit-container">
    <div>
        <span>e</span>
    </div>
</div>
<div class="digit-container">
    <div>
        <span>l</span>
    </div>
</div>
<div class="digit-container">
    <div>
        <span>l</span>
    </div>
</div>
<div class="digit-container">
    <div>
        <span>o</span>
    </div>
</div>

This is the JavaScript code I have come up with. I have managed to store these letters in an array.

wordList = document.querySelectorAll(".digit-container > div > span");
wordArray = [];

for (let i = 0; i < wordList.length; i++) {
    individualWord = wordList[i].innerHTML;
    wordArray.push(individualWord);
}

Now I would like JavaScript to send keypresses for this array of letters { "h", "e", "l", "l", "o" }. Basically when I'm pasting this code and press enter in the console, I would like JavaScript to press "Hello" with a milliseconds of delay in between keystrokes. How can I get JavaScript into press keys?

John Snape
  • 79
  • 5
  • Does this answer your question? [Is it possible to simulate key press events programmatically?](https://stackoverflow.com/questions/596481/is-it-possible-to-simulate-key-press-events-programmatically) –  Nov 08 '20 at 09:43

1 Answers1

0

Here is the solution.

const elements = document.querySelectorAll(".digit-container > div > span");
const chars = Array.from(elements).map((item) => item.textContent);

const delay = 1000;

let i = 0;

const pressKey = () => {
  setTimeout(() => {
    const char = chars[i];

    const event = new KeyboardEvent("keyup", {
      key: char
    });

    document.body.dispatchEvent(event);

    if (i !== chars.length - 1) {
      i++;
      pressKey();
    }
  }, delay);
};

pressKey();

document.body.addEventListener("keyup", (e) => {
  console.log(e.key);
});
<div class="digit-container">
    <div>
        <span>h</span>
    </div>
</div>
<div class="digit-container">
    <div>
        <span>e</span>
    </div>
</div>
<div class="digit-container">
    <div>
        <span>l</span>
    </div>
</div>
<div class="digit-container">
    <div>
        <span>l</span>
    </div>
</div>
<div class="digit-container">
    <div>
        <span>o</span>
    </div>
</div>
Sergey
  • 1,000
  • 8
  • 19