DEV Community

Discussion on: Creating a textarea character limit indicator

 
sarahokolo profile image
sahra 💫 • Edited

That's quite nice, but I do find some little issues that might arise with this approach. The first issue being that the warning text doesn't popup at the end, instead it's visible from start to finish, which doesn't look right. Also, I added two new texareas, but they didn't seem to be functional as the first two. Overall, having a function Inside a for loop like that isn't a very neat approach, makes the code unscalable and the function hard to maintain.

A cleaner and easier approach to achieve this for multiple textareas in the document is to separate the function from the for loop.

Here is my updated counter function:

const textareas = document.querySelectorAll(".txt");
const progressBars = document.querySelectorAll(".progress-bar");
const remCharsElems = document.querySelectorAll(".remaining-chars");

function charCounter(inputField, progress, warningTxt) {
  const maxLength = inputField.getAttribute("maxlength");
  const currentLength = inputField.value.length;

  const progressWidth = (currentLength / maxLength) * 100;
  progress.style.width = `${progressWidth}%`;
  warningTxt.style.display = "none";

  if (progressWidth <= 60) {
    progress.style.backgroundColor = "rgb(19, 160, 19)";
  } else if (progressWidth > 60 && progressWidth < 85) {
    progress.style.backgroundColor = "rgb(236, 157, 8)";
  } else {
    progress.style.backgroundColor = "rgb(241, 9, 9)";
    warningTxt.innerHTML = `${maxLength - currentLength} characters left`;
    warningTxt.style.display = "block";
  }
}
Enter fullscreen mode Exit fullscreen mode

This way the function logic has been separated and can be used anywhere.

Here is the forEach loop to get all the texareas in the document and apply the counter function to them.

textareas.forEach((textarea, i) => {
  textarea.oninput = () => charCounter(textarea, progressBars[i], remCharsElems[i]);
})
Enter fullscreen mode Exit fullscreen mode

Now, you can add as many texareas as you want, without needing to modify the JavaScript again.
You can check it out in the codepen below, where I added two new textareas with different maxlengths: