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
you can use
oninput
in your code.you can call your matching function in oninput like this
<input type="text" oninput="myFunction()">
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.
Just try this created a new div to retrieve corrected inputed letters in green
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:
The Dynamic Code Snippet of your code