JAVASCRIPT

Implement a Live Character Counter for Textarea Inputs

Learn to create a real-time character counter that updates as a user types into a textarea, providing immediate feedback on text length against a defined limit.

function setupCharacterCounter(textareaId, counterId, maxLength) {
  const textarea = document.getElementById(textareaId);
  const counter = document.getElementById(counterId);

  if (!textarea || !counter) {
    console.error('Textarea or counter element not found.');
    return;
  }

  const updateCounter = () => {
    const currentLength = textarea.value.length;
    counter.textContent = `${currentLength}/${maxLength} characters`;

    if (maxLength && currentLength > maxLength) {
      counter.style.color = 'red';
      textarea.classList.add('char-limit-exceeded'); // Add a class for styling
    } else {
      counter.style.color = ''; // Reset color
      textarea.classList.remove('char-limit-exceeded');
    }
  };

  textarea.addEventListener('input', updateCounter);

  // Initial update on load
  updateCounter();
}

// Usage example (HTML):
// <textarea id="myTextarea" rows="5" cols="50" maxlength="200"></textarea>
// <p id="charCounter"></p>
// <style>.char-limit-exceeded { border: 2px solid red; }</style>
//
// setupCharacterCounter('myTextarea', 'charCounter', 200);
How it works: This JavaScript snippet creates a real-time character counter for any textarea. It listens for `input` events on the textarea and dynamically updates a separate display element with the current character count and the maximum allowed length. It also provides visual feedback by changing the counter's color to red and adding a CSS class to the textarea if the limit is exceeded.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs