Hello! It's great to see you again.
In our last lesson, you added a "copy to clipboard" button, a small change that made your application much more convenient for the user. We focused on handling a click event and using the Clipboard API to perform an action.
Today, we'll continue improving the user interface by implementing another common and helpful feature: an input character counter for the text area. This will let the user know how much they've written in real-time, which is essential for tasks that might have a length limit. This lesson will help you achieve the goal of adding this counter using JavaScript.
Why Add a Character Counter?
A character counter provides immediate feedback to the user. It answers the question, "How much have I written?" This is particularly useful in AI applications where API calls might have character limits or where performance depends on the input size.
Here's what a character counter looks like in action:

Let's dive in and add this to our project.
Step 1: Update the HTML to Display the Count
First, we need a place in our HTML file to show the character count. The logical spot is right below the main text area. We will add a simple <div> element for this purpose.
Open your index.html file and find the <textarea> with the ID main-text-input. Add the new div right after it, like this:
<!-- ... inside your <body> tag ... -->
<div class="container">
<h1>AI Writing Assistant</h1>
<textarea id="main-text-input" placeholder="Enter your text here..."></textarea>
<!-- NEW: Add this div for the character counter -->
<div id="char-counter"></div>
<div class="tabs">
<!-- ... your tab buttons ... -->
</div>
<!-- ... the rest of your HTML ... -->
</div>
We've added a div with the ID char-counter. For now, it's empty. We will populate and update it using JavaScript.
Step 2: The JavaScript Logic for Real-Time Updates
The core of this feature is JavaScript. We need to listen for changes in the text area, count the characters, and update our new div. The best way to learn this is by seeing it built step-by-step.
The following video from the dcode channel provides an excellent walkthrough.
Creating a Characters Remaining Counter (for Text Areas) - JavaScript Tutorial
This tutorial, 'Creating a Characters Remaining Counter', clearly explains the entire process. We'll start by watching the sections on the HTML and JavaScript setup.
Please watch the video from 00:54 to 02:01 and from 02:54 to 07:55. As you watch, focus on these key concepts: HTML Structure: Notice how a <textarea> and a <div> are used, just like we did. Selecting Elements: See how document.getElementById is used to get references to the HTML elements. The input Event: This is a new event for us! It fires every time the user types, deletes, or pastes text into the text area. Counting and Updating: Observe how the code gets the length of the text (.value.length) and updates the textContent of the counter element.
Step 3: Integrating the Code into Our Project
Now that you've seen the concepts in the video, let's apply them to our script.js file. We will write code to:
- Define a maximum character limit.
- Select our text area and the new counter
div. - Add an
inputevent listener to the text area. - Inside the listener, calculate the remaining characters and update the counter's text.
Add the following code inside the DOMContentLoaded event listener in your script.js file. You can place it near the top, with your other element selections.
// --- Start of Character Counter Feature ---
// 1. Define the maximum number of characters allowed.
const MAX_CHARS = 5000;
// 2. Select the elements from the DOM.
const mainTextInput = document.getElementById('main-text-input');
const charCounter = document.getElementById('char-counter');
// 3. Set the initial text of the counter.
charCounter.textContent = `${MAX_CHARS} characters remaining`;
// 4. Add an event listener that triggers on every input change.
mainTextInput.addEventListener('input', () => {
const currentLength = mainTextInput.value.length;
const remainingChars = MAX_CHARS - currentLength;
// 5. Update the counter's text.
charCounter.textContent = `${remainingChars} characters remaining`;
});
Code Breakdown:
MAX_CHARS: We set a constant for the character limit. This makes it easy to change later.- We select the
textareaand our newchar-counterdivusing their IDs. - We set the initial text so the user knows the limit before they even start typing.
- The
addEventListener('input', ...)is the key. The function inside it runs every single time the user changes the content of the text area. - Inside the listener, we get the current number of characters with
mainTextInput.value.length. - Finally, we update the
textContentof our counterdivwith a new string showing the remaining characters.
Optional Enhancement: Adding Color Feedback
Good UI design gives users subtle clues. Let's make the counter turn red when the user is close to the character limit. This provides a helpful warning. The video we watched shows a great way to do this.
Creating a Characters Remaining Counter (for Text Areas) - JavaScript Tutorial
The last part of the dcode video demonstrates how to dynamically change the counter's color. This is a great touch to improve user feedback.
Please watch from 07:55 to 09:49. The video uses a clever one-line conditional (a ternary operator) to decide the color. This is a common and efficient pattern in JavaScript.
Let's update our event listener to include this logic. We'll make the text red if the remaining characters are 10% or less of the maximum.
// --- Updated 'input' event listener ---
mainTextInput.addEventListener('input', () => {
const currentLength = mainTextInput.value.length;
const remainingChars = MAX_CHARS - currentLength;
charCounter.textContent = `${remainingChars} characters remaining`;
// NEW: Add color-changing logic
// If remaining characters are less than 10% of the max, turn the text red. Otherwise, keep it black.
if (remainingChars < MAX_CHARS * 0.1) {
charCounter.style.color = 'red';
} else {
charCounter.style.color = 'black'; // Or whatever your default text color is
}
});
Now, when the user gets close to the 5000-character limit (below 500), the counter will automatically turn red!
Test your understanding!
Currently, our counter shows "X characters remaining". How would you modify the event listener to show the count in this format instead: "Current: Y / Total: X" (e.g., "Current: 250 / Total: 5000")?
Show answer
You would need to change the line that updates the textContent. Instead of using the remainingChars variable, you'd use currentLength and MAX_CHARS.
// The only line that needs to change is the one setting the textContent.
mainTextInput.addEventListener('input', () => {
const currentLength = mainTextInput.value.length;
const remainingChars = MAX_CHARS - currentLength;
// MODIFIED LINE:
charCounter.textContent = `Current: ${currentLength} / Total: ${MAX_CHARS}`;
// The color-changing logic still works the same!
if (remainingChars < MAX_CHARS * 0.1) {
charCounter.style.color = 'red';
} else {
charCounter.style.color = 'black';
}
});
Conclusion
Fantastic work! You have successfully added another key UI feature to your application. This character counter not only looks professional but also provides essential, real-time feedback to your users.
Key Takeaways:
- The
inputevent listener is the perfect tool for tracking changes in a<textarea>or<input>field in real-time. - You can get the content of a text area using the
.valueproperty. - The
.lengthproperty of a string tells you how many characters it contains. - By combining these with
textContentand.style, you can create dynamic and responsive UI elements that react instantly to user actions.
In our next lesson, we'll take a step back to look at the big picture. We'll focus on refining the overall layout and styling to give our application a more polished and cohesive user experience, preparing it for the final features.