ShrouderS
Reactiflux3y ago
15 replies
Shrouder

alforoan – 05-45 Oct 24

Hi, I would REALLY REALLY appreciate help with this typing game I'm working on.

const wordsArraySpan = document.querySelector(".words-array");
const input = document.querySelector(".input");
let inputArray = [];
let currentIndex = 0;

input.addEventListener("input", function (e) {
  const typedText = this.value.trim();
  const words = typedText.split(" ");
  let highlightedWords = [];

  for (let i = 0; i < wordsArray.length; i++) {
    const word = wordsArray[i];
    const isMatched = words.includes(word) || inputArray.includes(word);

    let highlightedWord = "";

    if (i === currentIndex) {
      for (let j = 0; j < word.length; j++) {
        if (j < typedText.length && word[j] === typedText[j]) {
          highlightedWord += `<span class="highlight">${word[j]}</span>`;
        } else {
          highlightedWord += word[j];
        }
      }
    } else {
      highlightedWord = word; // Use the original word for other words
    }

    highlightedWords.push(
      isMatched
        ? `<span class="highlight">${highlightedWord}</span>`
        : highlightedWord
    );

    if (isMatched && !inputArray.includes(word) && typedText === word) {
      if (e.data === " ") {
        inputArray.push(word);
        this.value = "";
        currentIndex++;
      }
    }
  }

  wordsArraySpan.innerHTML = highlightedWords.join(" ");
});


demonstration : https://gyazo.com/799af7944fe6cbd9b83050c47515748e
problem: as you could see from my gif above, when i finished typing "popper" and pressed spacebar to delete the text in input box, "p" in the next word was auto highlighted because it's in the same index as "p" in "popper". I've been taking forever to fix this, but I have no idea how I can fix it.
Was this page helpful?