Skip to main content

Create a Character Counter for Textareas with JavaScript: Step-by-Step Guide

· 3 min read

"Create a Character Counter for Textareas with JavaScript: Step-by-Step Guide"

Introduction

A character counter is a helpful feature for forms and text areas, allowing users to see how many characters they have entered and providing real-time feedback.

In this blog article, we'll guide you through the process of building a character counter using HTML, CSS, and JavaScript. You'll learn how to create a dynamic counter that updates as users type in a textarea field.

First we'll start with the HTML and CSS, then we'll add the JavaScript to make the counter work.

HTML Structure

Set up the HTML structure for your character counter.


<!DOCTYPE html>
<html>
<head>
<title>Character Counter</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<label for="textarea">Enter your text:</label>
<textarea id="textarea" rows="4" maxlength="100"></textarea>
<p><span id="counter">0</span> / 100 characters</p>
</div>
<script src="script.js"></script>
</body>
</html>

2. CSS Styling

Create a styles.css file to style your character counter.


body {
margin: 0;
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f9f9f9;
}

.container {
border: 1px solid #ddd;
padding: 20px;
width: 300px;
background-color: white;
}

label {
font-weight: bold;
margin-bottom: 10px;
display: block;
}

textarea {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
resize: none;
}

p {
margin-top: 10px;
}

#counter {
font-weight: bold;
}

3. JavaScript Character Counter

Implement the JavaScript logic for the character counter in your script.js file.


const textarea = document.getElementById('textarea');
const counter = document.getElementById('counter');

textarea.addEventListener('input', updateCounter);

function updateCounter() {
const currentLength = textarea.value.length;
const maxLength = parseInt(textarea.getAttribute('maxlength'));

counter.textContent = currentLength;

if (currentLength > maxLength) {
counter.style.color = 'red';
} else {
counter.style.color = 'black';
}
}

Conclusion

Congratulations! You've successfully built a character counter for textareas using HTML, CSS, and JavaScript. This feature provides users with real-time feedback on the number of characters they've entered, helping them stay within any specified limits. You can further customize the styling and behavior of the counter to match your website's design and requirements. By combining these technologies, you've added a practical and user-friendly element to your forms, improving the user experience and making your website more interactive.

We hope you found this tutorial helpful.

Happy Coding! 🎉