Typing Test using HTML, CSS & JavaScript

Design a Typing Speed Test using HTML, CSS & JavaScript

Typing Test using HTML, CSS & JavaScript

Welcome back to another mini-project. In today’s tutorial on Codewithrandom. We’ll learn how to make a Typing Speed Test which will test the typing accuracy of the user and the typing speed while he’s writing the sentence. In Today’s session, We will use HTML, CSS, and JavaScript to complete this Typing Test Project. The typing speed test is a game where you can check your typing speed like WPM (Word Per Minute), CPM (Character Per Minute), and Accuracy.

Project Description

Below We’ve described the Typing Test project description for better understanding.This Typing Speed Test game is completely begineer friendly project that is built using the HTML, CSS , and JavaScript.

Step 1
The HTML (Hypertext Markup Language) will help us to create the structure for the list with some necessary attributes and elements to make Typing Test Project.

Step 2
Then we will use CSS (Cascading Stylesheet) which will help us to style or design the project with suitable padding and alignment in the Typing Test Project.

Step 3
At last we will use JS (JavaScript) which will add a logic to make the Typing Test Project responsive from the user end.

I hope you have got an idea about the project.

HTML Code for Typing Test

First we’ll start with creating the structure of the Typing Test project for that as you can see the above code we have used all the necessary elements & attributes to setup the structure. Let us know code the CSS part to add styling and aligned the tags.

<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Typing Test</title>
    <!-- Google Fonts -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <div class="stats">
        <p>Time: <span id="timer">0s</span></p>
        <p>Mistakes: <span id="mistakes">0</span></p>
      </div>
      <div
        id="quote"
        onmousedown="return false"
        onselectstart="return false"
      ></div>
      <textarea
        rows="3"
        id="quote-input"
        placeholder="Type here when the test starts.."
      ></textarea>
      <button id="start-test" onclick="startTest()">Start Test</button>
      <button id="stop-test" onclick="displayResult()">Stop Test</button>
      <div class="result">
        <h3>Result</h3>
        <div class="wrapper">
          <p>Accuracy: <span id="accuracy"></span></p>
          <p>Speed: <span id="wpm"></span></p>
        </div>
      </div>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

Portfolio Website using HTML and CSS (Source Code)

CSS Code for Typing Test

Second comes the CSS code in which we have styled for the structure we have padded as well as aligned the Typing Test project so that it is properly situated and doesn’t get messy with suitable CSS elements. Now lets code the JavaScript part to make responsive.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #3066f6;
}
.container {
  width: 80vmin;
  padding: 50px 30px;
  background-color: #ffffff;
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  border-radius: 10px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
}
.stats {
  text-align: right;
  font-size: 18px;
  margin-bottom: 30px;
}
.stats span {
  font-weight: 600;
}
#quote {
  text-align: justify;
  margin: 50px 0 30px 0;
}
textarea {
  resize: none;
  width: 100%;
  border-radius: 5px;
  padding: 10px 5px;
  font-size: 16px;
}
button {
  float: right;
  margin-top: 20px;
  background-color: #3066f6;
  color: #ffffff;
  border: none;
  padding: 10px 30px;
  border-radius: 5px;
  font-size: 18px;
}
.result {
  margin-top: 40px;
  display: none;
}
.result h3 {
  text-align: center;
  margin-bottom: 20px;
  font-size: 22px;
}
.wrapper {
  display: flex;
  justify-content: space-around;
}
.wrapper span {
  font-weight: 600;
}
.success {
  color: #44b267;
}
.fail {
  color: #e81c4e;
}

JavaScript Code for Typing Test

Last stage of the project the JavaScript in which we have added the logical and coded as per the requirement with some conditions. We have defined each id from the HTML Code and make it responsive so that the project is responsive and works without any error. Let us see the Final Output of the project Typing Test using HTML, CSS & JavaScript (Source Code).

//Random Quotes Api URL
const quoteApiUrl = "https://api.quotable.io/random?minLength=80&maxLength=100";
const quoteSection = document.getElementById("quote");
const userInput = document.getElementById("quote-input");
let quote = "";
let time = 60;
let timer = "";
let mistakes = 0;

//Display random quotes
const renderNewQuote = async () => {
  //Fetch contents from url
  const response = await fetch(quoteApiUrl);

  //Store response
  let data = await response.json();

  //Access quote
  quote = data.content;

  //Array of characters in the quote
  let arr = quote.split("").map((value) => {
    //wrap the characters in a span tag
    return "<span class='quote-chars'>" + value + "</span>";
  });
  //join array for displaying
  quoteSection.innerHTML += arr.join("");
};

//Logic for comparing input words with quote
userInput.addEventListener("input", () => {
  let quoteChars = document.querySelectorAll(".quote-chars");
  //Create an arrat from received span tags
  quoteChars = Array.from(quoteChars);

  //array of user input characters
  let userInputChars = userInput.value.split("");

  //loop through each character in quote
  quoteChars.forEach((char, index) => {
    //Check if char(quote character) = userInputChars[index](input character)
    if (char.innerText == userInputChars[index]) {
      char.classList.add("success");
    }
    //If user hasn't entered anything or backspaced
    else if (userInputChars[index] == null) {
      //Remove class if any
      if (char.classList.contains("success")) {
        char.classList.remove("success");
      } else {
        char.classList.remove("fail");
      }
    }
    //If user enter wrong character
    else {
      //Checks if we alreasy have added fail class
      if (!char.classList.contains("fail")) {
        //increment and display mistakes
        mistakes += 1;
        char.classList.add("fail");
      }
      document.getElementById("mistakes").innerText = mistakes;
    }
    //Returns true if all the characters are entered correctly
    let check = quoteChars.every((element) => {
      return element.classList.contains("success");
    });
    //End test if all characters are correct
    if (check) {
      displayResult();
    }
  });
});

//Update Timer on screen
function updateTimer() {
  if (time == 0) {
    //End test if timer reaches 0
    displayResult();
  } else {
    document.getElementById("timer").innerText = --time + "s";
  }
}

//Sets timer
const timeReduce = () => {
  time = 60;
  timer = setInterval(updateTimer, 1000);
};

//End Test
const displayResult = () => {
  //display result div
  document.querySelector(".result").style.display = "block";
  clearInterval(timer);
  document.getElementById("stop-test").style.display = "none";
  userInput.disabled = true;
  let timeTaken = 1;
  if (time != 0) {
    timeTaken = (60 - time) / 100;
  }
  document.getElementById("wpm").innerText =
    (userInput.value.length / 5 / timeTaken).toFixed(2) + " wpm";
  document.getElementById("accuracy").innerText =
    Math.round(
      ((userInput.value.length - mistakes) / userInput.value.length) * 100
    ) + " %";
};

//Start Test
const startTest = () => {
  mistakes = 0;
  timer = "";
  userInput.disabled = false;
  timeReduce();
  document.getElementById("start-test").style.display = "none";
  document.getElementById("stop-test").style.display = "block";
};

window.onload = () => {
  userInput.value = "";
  document.getElementById("start-test").style.display = "block";
  document.getElementById("stop-test").style.display = "none";
  userInput.disabled = true;
  renderNewQuote();
};

100+ JavaScript Projects With Source Code ( Beginners to Advanced)

Final Output of Typing Speed Test

Below is CodePen Preview for the Typing Speed Test with free source code.

We have Successfully created our Typing Test using HTML, CSS & JavaScript. You can use this project for your personal needs and the respective lines of code are given with the code pen link mentioned above.

If you find out this Blog helpful, then make sure to search code with random on google for Front End Projects with Source codes and make sure to Follow the Code with Random Instagram page.

Code Idea – codingartist

Written By – Harsh Sawant

Code By – @harshh9

HAPPY CODING!!



Leave a Reply