Wednesday, June 26, 2024
HomeCSSCreate a Typing Take a look at Sport with Vanilla JavaScript

Create a Typing Take a look at Sport with Vanilla JavaScript


HTML Construction

Okay, let’s get began. The HTML construction will include the next parts;

  • A timer button
  • An <h3> tag containing the textual content to be typed.
  • An enter textual content for typing the phrases.
  • A reset button that can immediate the person to retake the take a look at as soon as the timer runs out.

We can be utilizing Bootstrap  to construct the  interface.

Let’s begin by including the heading contained in the common container.

1
<div class="container mt-5 text-center">
2
      <div class="row">
3
        <div class="col">
4
          <h1>TYPING SPEED TEST</h1>
5
        </div>
6
      </div>
7
  </div>
8
      

Subsequent, add the timer  countdown button and an empty <h3> aspect to replace the typing outcomes.

1
<div class="row mt-5">
2
    <div class="col">
3
      <button id="countdown" class="btn btn-primary btn-lg mb-3">60s</button>
4
      <h3 id="wpm" class="mt-3"></h3>
5
    </div>
6
 </div>

The following row will comprise the next parts

  • An <h3> tag containing  the textual content to be typed. The textual content can be added dynamically with JavaScript because the person sorts to make sure it doesn’t take up an excessive amount of house.
  • Beneath the <h3> tag, we may have the textarea enter the place the person can be typing.
1
<div class="row mt-5" id="foremost">
2
  <div class="col-9 mx-auto">
3
    <h3 id="phrase" class="display-6"></h3>
4
    <textarea
5
      class="form-control text_input mb-3"
6
      placeholder="Begin typing right here..."
7
    ></textarea>
8
  </div>
9
</div>

The final aspect is the reset button which, when clicked, will let the person play once more: This row containing the button will be hidden by default.

1
<div class="row mt-5" id="reset">
2
  <div class="col">
3
    <button id="reset_btn" class="btn btn-success btn-lg h3">Take the Take a look at Once more</button>
4
  </div>
5
</div>
6
</div>

CSS Performance

On prime of what Bootstrap offers us, we may even use some customized CSS types as proven under.

1
@import url("https://fonts.googleapis.com/css2?household=DM+Mono:ital,wght@0,300;0,400;0,500;1,300;1,400;1,500&show=swap");
2

3
  physique {
4
    font-family: "DM Mono", monospace;
5
  }
6
  
7
  h1 {
8
    font-weight: 900;
9
  }
10
  
11
  #phrase {
12
    min-height: 11rem; 
13
   
14
  }
15
  
16
  .right {
17
    coloration: inexperienced;
18
  }
19

20
  .incorrect {
21
    coloration: pink;
22
  }
23
  
24
  #reset {
25
    show: none;
26
  }

The inexperienced coloration can be utilized to the letters typed appropriately, whereas the pink coloration can be utilized to the incorrectly typed letters. When the person is typing, it’ll look one thing like this:

JavaScript Performance

With the construction and the styling taken care of, let’s get caught into the behaviour with some JavaScript. We’ll begin by creating the timer, so get the timer button aspect.

1
const timerElement = doc.getElementById("countdown");

Then, outline a length fixed, this represents the timer length of 1 min(60s)

Subsequent create a perform referred to as startTimer() . Contained in the perform, outline a timer variable and initialize it with the length fixed .

1
perform startTimer() {
2
  let timer = length;
3
  
4
  
5
}

Subsequent, we’ll use the setInterval() technique which runs a perform repeatedly at specified intervals. In our case, it’ll lower the timer by 1 each second and replace the timerElement with the brand new timer worth. When the timer reaches 0, the interval can be cleared to cease the countdown.

1
perform startTimer() {
2
  let timer = length;
3
  interval = setInterval(() => {
4
    timer--;
5
    timerElement.textContent = `${timer}s`;
6

7
  }, 1000);
8
}

If the timer reaches 0, we’ll clear it with the clearInterval() technique and set the textual content content material of the timerElement to “Time’s up.” Replace the startTimer() perform like this:

1
perform startTimer() {
2
  let timer = length;
3

4
  interval = setInterval(() => {
5
    timer--;
6
    timerElement.textContent = `${timer}s`;
7

8
    if (timer <= 0) {
9
      clearInterval(interval);
10
      timerElement.textContent = "Time's up!";
11
      
12
    }
13
  }, 1000);
14
}

The Phrase to Sort

The following step is to show a chunk of the textual content to be typed. The textual content appears like this:

1
const phrase = `Individuals typically search for methods to enhance their lives. They need to be pleased, wholesome, and profitable. 
2
To attain these objectives, they work onerous, spend time with household and pals, and revel in hobbies. 
3
Consuming nicely and staying energetic are vital for well being. 
4
Studying new issues and setting objectives may also help individuals develop.
5
Everybody has challenges, however staying constructive and targeted could make an enormous distinction.
6
Serving to others and being form may deliver pleasure. 
7
Life is a journey, and each day is an opportunity to make it higher.
8
Benefit from the little issues and respect what you have got. 
9
It is vital to remain related with others, talk brazenly, and pay attention fastidiously. 
10
Studying books, exploring new locations, and making an attempt new actions can increase our horizons. 
11
Balancing work and leisure helps preserve a wholesome way of life. 
12
Bear in mind to chuckle typically, love deeply, and stay totally. 
13
Taking time to replicate on our experiences and be taught from them can result in private development. 
14
The help of family members can present energy and luxury. 
15
Each second is a chance to create lasting reminiscences and construct a satisfying life.
16
In the long run, it isn't the years in your life that rely. It is the life in your years. - Abraham Lincoln`; 

Since we’re utilizing template literals to format the textual content, on the finish of every line, we have now white house, so we have to format the textual content to make sure the textual content has no pointless breaks and additional areas. 

1
const textual content = phrase.change(/[rn]+s*/g, ' ') .change(/s{2,}/g, ' '); ;

Within the code above, we use common expressions to scrub up the textual content by eradicating line breaks and decreasing a number of consecutive whitespace characters to a single house.

When the app hundreds for the primary time, we’ll present solely a portion of the textual content. Let’s use the splice() technique to get the primary 10 phrases of the textual content after which set the textContent of the phrase aspect to this string of the primary 10 phrases.

1
const phrase = doc.getElementById("phrase");
2
phrase.textContent = textual content.break up(" ").slice(0
3
  , 10).be part of(" ");

Because the person sorts, we additionally need to repeatedly add a portion of the textual content relying on the place the person has reached typing. For instance, three traces of textual content at each occasion can be a really perfect quantity.

Create a continuing displayLength to outline the size of the seen portion of the textual content based mostly on the typing place.

1
const displayLength = 80;

Subsequent, we’ll get the textual content enter and pay attention for the enter occasion. The enter occasion is triggered when a person sorts or deletes something within the enter space. We may even create a timerStarted variable and set it to false. timerStarted variable will make sure the timer doesn’t reset to 0 when the person is typing.

1
let timerStarted = false;
2

3
const textInput = doc.querySelector(".text_input");
4
textInput.addEventListener("enter", (e) => {
5

6
}

Within the occasion listener perform, we’ll create an if assertion that can be certain that the timer is began solely as soon as when the enter occasion is fired.

1
textInput.addEventListener("enter", (e) => {
2
  if (!timerStarted) {
3
    startTimer();
4
    timerStarted = true;
5

6
  }
7
}

Fetch the Typed Textual content

Subsequent,  let’s get the worth of the typedtext. typedtext is the textual content the person has typed and is obtained from the worth of the enter aspect. Initialise displayText, a variable which represents the portion of the textual content to be typed that can be proven to the person:

1
const typedText = textInput.worth;
2
 let displayText = "";

Subsequent, create a startIndex and a stopIndex, which is able to decide the beginning index of the textual content to be typed based mostly on the person’s typing place.

1
let startIndex = Math.max(0, typedText.size - displayLength / 2);
2
let endIndex = startIndex + displayLength;

Subsequent, we need to create a for loop that can iterate from the startIndex as much as the endIndex and throughout the bounds of the textual content to be typed.

Contained in the for loop, we’ll repeatedly examine if the present index is throughout the bounds of the typed textual content. If the character on the present index of the typed textual content matches the character on the identical index within the textual content to be typed, it means the person is typing appropriately. On this case, we’ll wrap the proper character in a span with a category that applies a inexperienced coloration to it.

If there may be an index mismatch, the person has misspelled the present index, we’ll wrap it in a span class and apply a pink coloration.

Because the person sorts, the colour highlighting can be displayed on the aspect containing the displayed textual content in real-time.

Replace the Outcomes

The final step is to replace the outcomes as soon as the timer reaches 0. Create a perform referred to as updateResults() which is able to appear to be this:

1
perform updateTyping() {
2
  mainContainer = doc.getElementById("foremost");
3
  mainContainer.type.show = "none";
4
  const wordsTypedValue = doc.querySelector(".text_input").worth;
5
  const wordsTyped = wordsTypedValue.trim().break up(/s+/).size
6
  wpm.textContent = `Your velocity was: ${
7
    (wordsTyped * 60) / length
8
  } WPM `;
9

10
  resetContainer.type.show = "block";
11
}

After the timer length reaches 0:

  • we’ll conceal the textual content being typed and the textarea enter aspect.
  • Then, we’ll get the worth of the enter, which is able to signify the variety of phrases the person has typed within the length of the 1-minute timer.
  • const wordsTyped=wordsTypedValue.trim().break up(/s+/).size will break up the content material typed and get the entire variety of phrases typed.
  • Then we’ll replace the typing velocity with the components  (wordsTyped*60) /length.
  • Lastly, we’ll show the reset button. The button will immediate the person to retake the textual content.

In your startTimer() perform, replace it to invoke the updateResults() when the timer reaches 0.

1
perform startTimer() {
2
  let timer = length;
3
//   let interval;
4
  interval = setInterval(() => {
5
    timer--;
6
    timerElement.textContent = `${timer}s`;
7

8
    if (timer <= 0) {
9
      clearInterval(interval);
10
      timerElement.textContent = "Time's up!";
11
      updateTyping();
12
    }
13
  }, 1000);
14
}

 

When the timer ends, you need to see one thing like this:

As a reminder, right here is the demo:

Conclusion

This tutorial has lined create a completely functioning typing take a look at software with Vanilla JavaScript. You’ve discovered quite a bit! We lined many JavaScript ideas, akin to occasion dealing with, DOM manipulation, string manipulation, the Math perform, conditional logic, for loops, and dealing with intervals.

You’ll be able to enhance the applying by including extra options, akin to completely different deadlines, accuracy, errors and so forth. Good luck! 

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments