Build a Real Time Counter - Build a Real Time Counter

Tell us what’s happening:

Hi team, I need help to pass the last step. It works like the example project, or I think so.

Your code so far

<!-- file: index.html -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Real Time Counter</title>
    <link rel="stylesheet" href="./styles.css">
</head>

<body>
    <main>
        <h1>Real-time character counter</h1>
        <textarea id="text-input" placeholder="Type something..."></textarea>
        <p id="char-count">Character Count: <span>0/50</span></p>
    </main>
    <script src="./script.js"></script>
</body>


</html>
/* file: styles.css */
* {
  box-sizing: border-box;
}

.red-txt {
  color: red;
}
/* file: script.js */
const textInputElm = document.getElementById("text-input");
const charCountElm = document.querySelector("#char-count");
const counterElm = document.querySelector("#char-count span");

textInputElm.addEventListener("input", () => {
  processInput(textInputElm.value);
})

function processInput(userInput) {
  const inputArr = [];
  let strLen = userInput.length;

  if (strLen === 50) {
    charCountElm.classList.add("red-txt");
  } else if (strLen > 50) {
    inputArr.push(...userInput);
    inputArr.pop();
    textInputElm.value = inputArr.join("");
    strLen = inputArr.length;    
  } else {
    charCountElm.classList.remove("red-txt");
  }

  updateCounter(strLen);
}

function updateCounter(count) {
  counterElm.textContent = `${count}/50`;
}

Your browser information:

User Agent is: Mozilla/5.0 (X11; CrOS x86_64 14541.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36

Challenge Information:

Build a Real Time Counter - Build a Real Time Counter

Does your code work if you paste in text that is more than fifty characters long?

OK, thanks so much for your reply. Thats make me think deeper and find a better solution that passed the test. Here is the code:

function processInput(userInput) {
  const inputArr = [];

  let strLen = userInput.length;
  
  if (strLen >= 50) {
    inputArr.push(...userInput.slice(0,50));
    textInputElm.value = inputArr.join("");
    strLen = inputArr.length;
    charCountElm.classList.add("red-txt");   
  } else {
    charCountElm.classList.remove("red-txt");
  }
  
  updateCounter(strLen);
}