JS function does not change the color of the HTML text if it is repeated

Oleg Gulevskyy :

I struggled to select a title for this question, but I will do my best to explain below.

I have this checker made, that checks words from input one by one and if the word input correctly - it changes the color to green. It does it by splitting input into separate words and place it in the array.

What I see though is that if there is a repeatitive word in the text that I am comparing input words against, it does not change the color. Why would that be? The way I see my function of changing the color takes words' position in the array, not its value, and then simply adds the color for an html element.

let text = document.querySelector('.card-body').innerHTML;
let splitText = text.split(' ');

let userInput = document.querySelector('.form-control');
userInput.addEventListener('input', acceptInput)

let correctWords = [];
let mistakes = 0;
let words = [];


function acceptInput() {
    userInput.onkeydown = function(e){
        if(e.keyCode == 32){
            words = userInput.value.split(' ');        
            console.log(words); 
            console.log(splitText);
            let position = words.length-1;
            compareWordsArrays(position);
        }
    }
}

function compareWordsArrays(position) {
    
    for(i = position; i < words.length; i++) {
        if(words[i] === splitText[i]) {
            console.log(`Correct word detected: ${words[i]}`);
            let wordIndex = words.indexOf(words[i]);
            changeColor(wordIndex);

        } else {
            console.log('Incorrect word;');
            mistakes += 1;
            console.log(mistakes);
            
        }
    }
    
}

function changeColor(pos) {
    splitText[pos]="<font color=green>"+splitText[pos]+"</font>";
    let c = splitText.join(' ');
    document.querySelector('.card-body').innerHTML = c;
}
 <div class="card">
    <div class="card-body">Random text that appears from some generator or some stuff. But it needs to have quite few text, actually.
     </div>
</div>
<input type="text" class="form-control">

In my example you can see word "some" repest twice in the sentence, and second word "some" is not being changed though it does not count second word as a mistake neither I hope I am clear enough.

Laurent S. :

Just change

if(words[i] === splitText[i]) {
        console.log(`Correct word detected: ${words[i]}`);
        let wordIndex = words.indexOf(words[i]);
        changeColor(wordIndex);

    }

To

if(words[i] === splitText[i]) {
        console.log(`Correct word detected: ${words[i]}`);
        changeColor(i);

    }

As:

  • There's no point looking for an index you already know (i in this case)
  • indexOf only returns the first occurence index, hence your script working only for the first occurence...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=346849&siteId=1