Building a Live Textarea Character Count Limit with CSS3 and jQuery




Dynamic character counters are a common feature which I see requested frequently by web developers. You may have a form input field or textarea for users to enter data but want to limit the content. You could do this using maxlength which has been a property since the HTML4 specs. However we want to provide a more responsive UI so the user is aware of the limitations.

In this tutorial I’ll demonstrate how we can build a simple character limit counter using jQuery. As you enter text into the form field a live numerical update will display how many characters you’ve entered so far. This gives the user a better idea of how much they can enter and where the limit ends. And this effect is so easy to replicate, you shouldn’t have any problems porting it over into your own website layout.

JavaScript textarea character count limit tutorial preview

Live DemoDownload Source Code

Building the Document

Let’s start off by constructing the bare-bones HTML5 template which is commonplace in web development. I’m using the latest jQuery library hosted by Google along with a custom web font.

<!doctype html>
<html lang="en-US">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Textarea Character Limit with jQuery</title>
  <meta name="author" content="Jake Rocheleau">
  <link rel="stylesheet" type="text/css" href="styles.css">
  <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=ABeeZee">
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
  <script type="text/javascript" src="txtlimit.js"></script>
<!--[if lt IE 9]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>

You’ll notice I’ve created two separate documents for our CSS styles and the jQuery code. This amount of code doesn’t render itself to a custom plugin, especially since there is a decent amount of customization required. But it should be easy enough for anybody fairly well-versed in JS to go through and edit.

The body content is also very straightforward since my demo focuses on minimalism. I’ve created a paragraph with the ID #counter to update as the user enters some text. We are targeting an internal span element which encapsulates the number count.

<body>
  <div id="w">
    <h1>Live Textarea Count Limit</h1>
    <h3 class="desc">Text is limited up to 120 characters</h3>
  	
    <p id="counter"><span>0</span> characters</p>
  	
    <textarea name="text" id="text" class="txt" tabindex="1"></textarea>
  </div>
</body>
</html>

The only other important piece of information is the ID attributed to your text field. As an alternative you may target class names so that you can use this effect on multiple input fields. But within my code we’re just going to target all textareas on the page, save for simplicity.

Rendering JavaScript

Let’s now jump into the txtlimit.js file which holds all of our jQuery code. The first couple lines setup the document ready() clause so we don’t execute anything until the DOM has finished loading. I am also using a general variable to hold the max number of characters – feel free to change this to anything you like.

$(document).ready(function(){
  var limitnum = 120; // set your int limit for max number of characters

To make the code a bit cleaner I’m going to define a custom function which handles all our effects. Then we can call this function every time the user enters a key somewhere targeting a textarea element. This also makes it easier for you to write custom functions pertaining towards input fields instead.

function limits(obj, limit) {
  var cnt = $("#counter > span");
  var txt = $(obj).val(); 
  var len = txt.length;
    
  // check if the current length is over the limit
  if(len > limit){
    $(obj).val(txt.substr(0,limit));
    $(cnt).html(len-1);
  } 
  else { 
    $(cnt).html(len);
  }
     
  // check if user has less than 20 chars left
  if(limit-len <= 20) {
    $(cnt).addClass("warning");
  }
}

We define two parameters for this function to work – the textfield object we’re targeting and the character limit number. Inside the function we define variables for the counter element, the current text value and the length of that text. We are using all these values to update for every keyup event when the user releases a key.

The first bit of logic checks if we have the current text value over the limit. If so we edit the HTML to remove the last character entered by the user. This can be accomplished using the JavaScript substr() method. We are also updating the current counter number to display a new total.

Otherwise if the text is still less than our limit we just update the counter number. Each time the function runs we are also checking if the user is within 20 characters or less of the total limit. If they only have < 20 characters left then we add a .warning class onto the counter span element. This changes the number’s color from bright purple to red, signifying the limit is drawing closer.

Applying JS Event Handlers

Now with this custom function totally completed we can add the final piece to our script. I’ll be using the .keyup() event handler to run this function every single time a key is entered into any textarea. The limiting() function only needs 2 parameters – the 1st is targeting our currently focused textarea while the 2nd should be our max characters variable.

$('textarea').keyup(function(){
  limits($(this), limitnum);
});

Then with this addition we can close the JS file and it should all work perfectly. Nothing overly complex unless you are unfamiliar with building functions. This script may bug out if you include it on every page in your website, so try to keep it only on pages where you need this effect. Also it’s good if you can target a specific textarea instead of using the generic $(‘textarea’) selector.

Some Refined CSS Techniques

In this last segment I just want to copy over a few custom CSS styles I’m using in the demo page. Noticeably I have wrapped the current update number in a span tag so we can style this a bit differently than the other text.

#counter { font-size: 1.3em; color: #7e7e7e; margin-bottom: 9px; }
#counter span { font-style: italic; font-size: 2.1em; line-height: 1.55em; color: #a99bb1; }

#counter span.warning { color: #b66875; }

.txt { 
outline: none; 
width: 65%; 
height: 130px; 
padding: 9px 16px; 
font-size: 1.5em; 
line-height: 1.35em; 
color: #454545; 
border-top: 1px solid #c1c1c1; 
border-left: 1px solid #b7b7b7; 
border-bottom: 1px solid #818181; 
border-right: 1px solid #818181; 
box-shadow: 0px 1px 1px rgba(0,0,0,0.35); 
}

I’m styling the counter much larger and using a brighter color to stand out from the static page text. Also the warning class should override the default color so we have a much darker red as the limit is getting closer to being reached. This is a nice UX effect so the user knows they are running out of space to continue typing.

And finally the .txt style properties are all based for the page textarea. I am using plenty of padding so there is room for the text to fit. But also I’ve colored the borders differently on either side so it looks like the box has a shine around the edges. Also a small box-shadow hanging off the edge applies some wonderful CSS3 techniques in supported browsers.

JavaScript textarea character count limit tutorial preview

Live DemoDownload Source Code

Conclusion

This tutorial shows just how easily we can build full form validation effects with just a bit of jQuery. My demo includes a simple textarea but you could perform this method with any input text box. It’s a method defined by good user experience and some pleasing aesthetics.

But feel free to check out the live demo and grab a copy of my source code. You have the freedom to play around with my files and edit the code to your liking. Of course, you can quickly implement something similar on your own website by changing the initial script variables. If you have any other comments or questions feel free to share with us in the discussion area below.


Jake Rocheleau

About the author:

Jake is a creative designer, illustrator, and web developer. He frequently writes articles involving new-age design concepts and freelance management skills. You can find him in Google or follow his tweets @jakerocheleau

Comments:

Scroll back to the top
Content


Receive the top stories from SpyreStudios and the Splashpress Media network every week, right in your Inbox. Relevant and timely content is yours for FREE!