skip to Main Content

I am currently making a typing game. I have two variables; the first is the text that the user needs to type, and the second is the text the user has to is currently typing.

I have been able to make it so when the program can detect if the two variables are equal. But also when the text so far is equal to the text they need to write. For example if you need to type "test" and you’ve only typed "te" it will still be considered correct. Because you haven’t made any mistakes so far.

Anyway, I want the individual letters / characters to be highlighted when its either correct or incorrect. Because at the moment it will only highlight the entire word.

// Variables
let textBox = document.getElementsByClassName("text-box")[0];
let textShownInWebPage = document.getElementsByClassName("text-to-type")[0];
let typedValue;
let typedValueArray;
let displayText = "Just some sample text."
let characterArray = displayText.split("");
let i;

const run = () => {
    typedValue = textBox.value;

    let isCorrect = true;

    for (i = 0; i < typedValue.length; i++) {
      if (typedValue[i] !== displayText[i]) {
        isCorrect = false;
        break;
      }
    }

    if (isCorrect) {
      console.log("correct");
      textShownInWebPage.style.backgroundColor = "#f0290e";
    } else {
      console.log("incorrect");
      textShownInWebPage.style.backgroundColor = "#eb2323";
<div><span class="text-to-type">Just some sample text.</span></div>
<textarea class="text-box" rows="8" cols="55" oninput="run()"></textarea>

<!-- The line below is for JavaScript -->
<script src="index.js"></script>

I have tried using this line of code but it only creates error messages and I’m unsure why.

textShownInWebPage[i].style.backgroundColor = "#eb2323";

5

Answers


  1. you can use oninput in your code.
    you can call your matching function in oninput like this <input type="text" oninput="myFunction()">

    Login or Signup to reply.
  2. Here is a simple first attempt:
    As long as there have not been any errors in the typed text, that portion will be shown with a green background in the div above. Unfortunately, once an error is encountered, the hilighting will be removed for the whole text.

    const [txt,box]=[".text-to-type",".text-box"].map(sel=>document.querySelector(sel));
    function run(){
     txt.innerHTML=txt.textContent.replace(box.value,"<span class="ok">$&</span>");
    }
    .ok {background-color: green }
    <div><span class="text-to-type">Just some sample text.</span></div>
    <textarea class="text-box" rows="8" cols="55" oninput="run()"></textarea>
    Login or Signup to reply.
  3. Just try this created a new div to retrieve corrected inputed letters in green

    let textBox = document.getElementsByClassName("text-box")[0];
    let textShownInWebPage = document.getElementsByClassName("text-to-type")[0];
    let correctTypedLetters = document.querySelector(".typed-result");
    let typedValue="";
    let typedValueArray;
    let displayText = "another word"
    let characterArray = displayText.split("");
    let i;
    
    
    textShownInWebPage.textContent= `${displayText}`
    const run = () => {
        typedValue = textBox.value;
        let isCorrect = true;
        let counter = 0
        for (i = 0; i < typedValue.length; i++) {
            if (typedValue[i] !== displayText[i]) {
                isCorrect = false;
                alert('Letter is false')
                break;
            }else{
                if(counter==0){correctTypedLetters.textContent = ""}
                let correctLetter = characterArray[counter]
                // textShownInWebPage.textContent += `${correctLetter}`
                correctTypedLetters.textContent += `${correctLetter}`
                correctTypedLetters.style.color = "green"
                correctTypedLetters.style.fontSize = "20px"
                counter++
                if (counter===characterArray.length){
                    setTimeout(()=>{
                        alert('you won')
                        correctTypedLetters.textContent = ""
                    },450)
                    counter=0
                    return
                }
                
            }
    
        }
    
        if (isCorrect) {
            console.log("correct");
            textShownInWebPage.style.backgroundColor = "#f0290e";
        } else {
            console.log("incorrect");
            textShownInWebPage.style.backgroundColor = "#eb2323";
        }
    };
    <body>
        
        <div><span class="text-to-type"></span></div>
        <div class="typed-result"></div>
        <textarea class="text-box" rows="8" cols="55" oninput="run()"></textarea>
    
        <!-- The line below is for JavaScript -->
        <script src="script.js"></script>
    
    </body>
    Login or Signup to reply.
  4. There are serious issues of logic in your code.
    Any variables that are set outside of a function, can become inaccessible outside of it.

    here’s the correct and working Javascript:

    // Variables
    let textBox ;
    let textShownInWebPage;
    let typedValue;
    let typedValueArray;
    let i;
    
    var coloring = function(isCorrect){
        var textShownInWebPage = document.getElementsByClassName("text-to-type")[0];
        if (isCorrect) {
            console.log("correct");
            textShownInWebPage.style.backgroundColor = "green";
        } else {
            console.log("incorrect");
            textShownInWebPage.style.backgroundColor = "red";
        }
    }
    
    const run = () => {
    
        let displayText = "Just some sample text.";
        let characterArray = displayText.split("");
        
        let textBox = document.getElementsByClassName("text-box")[0];
        let typedValue = textBox.value;
        let isCorrect = true;
    
        for (i = 0; i < typedValue.length; i++) {
            if (typedValue[i] !== displayText[i]) {
                isCorrect = false;
                break;
            }
        }
        coloring(isCorrect);
    };
    
    Login or Signup to reply.
  5. The Dynamic Code Snippet of your code

      let textToType = document.getElementById("text-to-type");
      let textBox = document.getElementsByClassName("text-box")[0];
      let typedValue;
      let displayText = "Just some sample text."; // This text will add to text-to-type div 
      let getTextSpan = textToType.getElementsByTagName("span");
    
      window.onload = () => {
        for (var i in displayText) {
          const spanTag = document.createElement("span");
          const textNode = document.createTextNode(displayText[i]);
          spanTag.appendChild(textNode);
          textToType.appendChild(spanTag);
        }
      };
    
      const run = () => {
        typedValue = textBox.value;
    
        let isCorrect = true;
    
        for (let i in displayText) {
        // This nested loop will prevent red colour to show on the text that isn't  typed yet
          for (let j in typedValue) {
            if (typedValue.length <= displayText.length) {
              if (typedValue[j] !== displayText[j]) {
                getTextSpan[j].style.color = "red";
              }
            }
          }
    
          if (typedValue[i] === displayText[i]) {
            getTextSpan[i].style.color = "blue";
          } else {
          // black color for those chars that didn't typed yet
            getTextSpan[i].style.color = "black";
          }
        }
      };
    <body>
    
    <!-- The Text will automatically add by javascript varaible textToType -->
    
    <div id="text-to-type"></div> 
    <textarea class="text-box" rows="8" cols="55" oninput="run()"></textarea>
    
    </body>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search