Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Creating an if statement for colours changing depending on correct answer?

Edrol97

Bronze Coder
Hi all,

I'm wondering if I'm right here, think I'm on the right track but don't know. I've got a word based game that I've made on politics. The current version is currently live and can be seen here. I want to conditionally change the colors of the boxes based on the correct letters being inputted.
JavaScript:
if (correctLetters.length === word.length) {style.color=green}
else
(style.color=#b50938)

Thanks,

Eliot
 
A couple potential issues:

1) Without being able to see the rest of the code, wondering if your logic is incorrect. Is there ever a case where the correct letters length equals the word length but it's not displaying the right word to the user? Checking via length seems wrong, but might be right based on the rest of your code.

2) To style the color, you need to be attaching that to an element, such as this: W3Schools.com
 
The full code

JavaScript:
const inputs = document.querySelector(".inputs"),
  hintTag = document.querySelector(".hint span"),
  guessLeft = document.querySelector(".guess-left span"),
  wrongLetter = document.querySelector(".wrong-letter span"),
  resetBtn = document.querySelector(".reset-btn"),
  typingInput = document.querySelector(".typing-input");
let word,
  maxGuesses,
  incorrectLetters = [],
  correctLetters = [],
  gamelength = [];
function randomWord() {
  let ranItem = wordList[Math.floor(Math.random() * wordList.length)];
  word = ranItem.word;
  maxGuesses = word.length >= 5 ? 8 : 6;
  correctLetters = [];
  incorrectLetters = [];
  hintTag.innerText = ranItem.hint;
  guessLeft.innerText = maxGuesses;
  wrongLetter.innerText = incorrectLetters;
  let html = "";
  for (let i = 0; i < word.length; i++) {
    html += `<input type="text" disabled>`;
    inputs.innerHTML = html;
  }
}
randomWord();
function initGame(e) {
  let key = e.target.value.toLowerCase();
  console.log(word);
  if (
    key.match(/^[A-Za-z]+$/) &&
    !incorrectLetters.includes(` ${key}`) &&
    !correctLetters.includes(key)
  ) {
    if (word.includes(key)) {
      for (let i = 0; i < word.length; i++) {
        if (word[i] == key) {
          correctLetters += key;
          inputs.querySelectorAll("input")[i].value = key;
        }
      }
    } else {
      maxGuesses--;
      incorrectLetters.push(` ${key}`);
    }
    guessLeft.innerText = maxGuesses;
    wrongLetter.innerText = incorrectLetters;
  }
  typingInput.value = "";
  setTimeout(() => {
    if (correctLetters.length === word.length) {
      alert(`Congrats! You found the word ${word.toUpperCase()}`);
      return randomWord();
    } else if (maxGuesses < 1) {
      alert("Game over! You don't have remaining guesses");
      for (let i = 0; i < word.length; i++) {
        inputs.querySelectorAll("input")[i].value = word[i];
      }
    }
  }, 100);
}

resetBtn.addEventListener("click", randomWord);
typingInput.addEventListener("input", initGame);
inputs.addEventListener("click", () => typingInput.focus());
document.addEventListener("keydown", () => typingInput.focus());

if (currentQuestion < quizData.length) {
  showQuestion();
} else {
  showResult();
}

function showResult() {
  quiz.innerHTML = `<h1>${getScoreMessage()}</h1>
    <p>Your score: ${score}/${quizData.length}</p>
  `;
}

showHint();
 
Hey Eliot,

You're definitely on the right track! To change the colors of the boxes based on correct letters, you'll need to add some styling logic inside your initGame() function where you're handling the correct guesses. Instead of just setting the letter, you can conditionally apply styles to each input box.

Here’s an updated version of the part that checks for correct letters and changes the box colors:

JavaScript:
if (word.includes(key)) {
  for (let i = 0; i < word.length; i++) {
    if (word[i] == key) {
      correctLetters += key;
      inputs.querySelectorAll("input")[i].value = key;
      inputs.querySelectorAll("input")[i].style.backgroundColor = "green"; // Set color to green for correct letters
    }
  }
} else {
  maxGuesses--;
  incorrectLetters.push(` ${key}`);
  for (let i = 0; i < word.length; i++) {
    inputs.querySelectorAll("input")[i].style.backgroundColor = "#b50938"; // Set color to red for wrong guesses
  }
}

This will change the background color of the input fields to green when a correct letter is guessed and to red for incorrect guesses. You can adjust the styles as needed for your game’s design.

Also, a minor tweak in your correctLetters array – it's a string concatenation right now, but it would be better to use an array for handling letters, so you can use methods like .includes() properly.

JavaScript:
correctLetters = []; // Initialize as an array

// Then add letters like this:
correctLetters.push(key);

Let me know how it works, or if you have any questions about further customization!
 
Hey Eliot,

You're definitely on the right track! To change the colors of the boxes based on correct letters, you'll need to add some styling logic inside your initGame() function where you're handling the correct guesses. Instead of just setting the letter, you can conditionally apply styles to each input box.

Here’s an updated version of the part that checks for correct letters and changes the box colors:

JavaScript:
if (word.includes(key)) {
  for (let i = 0; i < word.length; i++) {
    if (word[i] == key) {
      correctLetters += key;
      inputs.querySelectorAll("input")[i].value = key;
      inputs.querySelectorAll("input")[i].style.backgroundColor = "green"; // Set color to green for correct letters
    }
  }
} else {
  maxGuesses--;
  incorrectLetters.push(` ${key}`);
  for (let i = 0; i < word.length; i++) {
    inputs.querySelectorAll("input")[i].style.backgroundColor = "#b50938"; // Set color to red for wrong guesses
  }
}

This will change the background color of the input fields to green when a correct letter is guessed and to red for incorrect guesses. You can adjust the styles as needed for your game’s design.

Also, a minor tweak in your correctLetters array – it's a string concatenation right now, but it would be better to use an array for handling letters, so you can use methods like .includes() properly.

JavaScript:
correctLetters = []; // Initialize as an array

// Then add letters like this:
correctLetters.push(key);

Let me know how it works, or if you have any questions about further customization!
Hi Simon,

Apologies for being a muppet. Where do I add this in the InitGame() function? I've tried adding it after what's already there and before but can't seem to make it function.

Thanks,

Eliot
 
Hey Eliot,

No worries at all, you're not a muppet! 😄 Let me help clarify where to add the code in the initGame() function.

You should add the color-changing part inside the block where you handle correct and incorrect guesses. Specifically, after you update the correctLetters and inputs. So, it should look something like this:

JavaScript:
function initGame(e) {
  let key = e.target.value.toLowerCase();
  
  if (key.match(/^[A-Za-z]+$/) && !incorrectLetters.includes(` ${key}`) && !correctLetters.includes(key)) {
    
    if (word.includes(key)) {
      for (let i = 0; i < word.length; i++) {
        if (word[i] == key) {
          correctLetters.push(key);  // Add the correct letter to the array
          inputs.querySelectorAll("input")[i].value = key;
          inputs.querySelectorAll("input")[i].style.backgroundColor = "green"; // Set to green for correct letters
        }
      }
    } else {
      maxGuesses--;
      incorrectLetters.push(` ${key}`);
      
      // Set background color to red for incorrect guess
      for (let i = 0; i < word.length; i++) {
        inputs.querySelectorAll("input")[i].style.backgroundColor = "#b50938";
      }
    }

    guessLeft.innerText = maxGuesses;
    wrongLetter.innerText = incorrectLetters;
  }

  typingInput.value = "";
  
  // Rest of the function remains the same
}

This should be placed inside the condition where you check if the letter is in the word or not. After updating the input box with the letter, it will change the background color to green for correct guesses, and if it’s an incorrect guess, the boxes will turn red.

Give that a try, and let me know if it's working for you now!
 

New Threads

Buy us a coffee!

Back
Top Bottom