1

When the user begins typing it displays incorrect and will not display correct. How do I code this to allow the user to type the complete word before it displays the message. I am a beginner so any help would be appreciated. Thanks.

window.addEventListener('keydown', randomD);
 
function randomD(event) {
const wordList = ['Carvedilol', 'Histrelin', 'Kadcyla', 'Mavyret', 'Paracetamol',     'Raloxifene', 'Saxagliptin'];
const random = Math.floor(Math.random() * wordList.length);
const ranWord = wordList[random];
const display = document.querySelector("#wordDisplay");
const output = document.querySelector("typedWord");
if (event.keyCode === 32) {  
  display.innerHTML = ranWord;
  setTimeout(time, 6000);
}
 if (validateWord !== ranWord) {    
    const timeDisplay = document.querySelector("#timeDisplay");
    timeDisplay.innerHTML = "Incorrect!";
  }

 if (validateWord == ranWord) {
  const timeDisplay = document.querySelector("#timeDisplay");
    timeDisplay.innerHTML = "Correct!";
 }
  
   if (event.keyCode === 32) {
      display.innerHTML = ranWord;
      setTimeout(time, 6000);
      timeDisplay.innerHTML = "";
    } 

function time(event) {
const timeDisplay = document.querySelector("#timeDisplay");
timeDisplay.innerHTML = "Time Up!";
}

function validateWord(field) {
  let output = document.querySelector("#typedWord").value; 
  }
      
}
robH
  • 29
  • 1

1 Answers1

0

There are three ways to do it

  1. You wait for some time after a onkeyup in the input/text-area area and then apply your validation, however if your wait time is more than user next key press you need to cancel the validation to let the user complete the input.
  2. You wait for user to come out of the input/text-area using onfocusout event handler and then apply your validation.
  3. Alternatively checkout a 3rd party library already built to handle this scenario https://stackoverflow.com/a/29131816/7845523