
I decided to challenge myself by creating a typing test using Javascript and integrating it into a plain HTML page. My goal was to generate entirely random words for the test. I’ve included the code.
This code example was created in HUGO and is served from AWS S3 and Cloudfront. I’m running this site for free. I plan on detailing the setup in a future blog post.
Give it a try
This is a 30 second typing test. The timer starts when you start typing.
Type the following word as fast as you can:
Here is the code:
HTML
<form>
<p id="word"></p>
<input id="input" type="text" placeholder="Start Typing" autofocus/>
<p id="time">Your time will display here.</p>
</form>
<script src="js/typing-test.js"></script>
Javascript
The filename for this javascript is “js/typing-test.js”
// Array of words
let words = []; // replace with your words
// Select a random word
fetch("https://random-word-api.herokuapp.com/word?number=120&length=6")
.then((response) => response.json())
.then((herokuWords) => {
// 'words' is an array of 120 random words
words = herokuWords;
const wordElement = document.getElementById("word");
randomWord = words[Math.floor(Math.random() * words.length)];
wordElement.textContent = randomWord;
})
.catch((error) => console.error("Error:", error));
let randomWord = words[Math.floor(Math.random() * words.length)];
// Display the word to the user
const wordElement = document.getElementById("word");
wordElement.textContent = randomWord;
let startTime;
let wordCount = 0;
// Start the timer when the user starts typing
const inputElement = document.getElementById("input");
inputElement.addEventListener("input", startTimer);
function startTimer() {
if (startTime) return;
startTime = Date.now();
// Stop the test after 30 seconds
setTimeout(endTest, 30000); // 30000 milliseconds = 30 seconds
}
// Check the user's input
inputElement.addEventListener("input", checkInput);
function checkInput(e) {
console.log(e.target.value);
console.log(randomWord);
if (e.target.value === randomWord) {
wordCount++;
e.target.value = "";
e.target.placeholder = "";
// Select a new random word
randomWord = words[Math.floor(Math.random() * words.length)];
wordElement.textContent = randomWord;
}
}
function endTest() {
// Calculate words per minute
const endTime = Date.now();
const timeTaken = (endTime - startTime) / 60000; // in minutes
const wordsPerMinute = wordCount / timeTaken;
// Display the result
document.getElementById("time").textContent = `Words per minute: ${Math.round(
wordsPerMinute
)}`;
wordElement.textContent = "Test complete!";
// Prevent further input
inputElement.disabled = true;
}