SpyreStudios

Web Design and Development Magazine

  • Design
  • Showcase
  • Inspirational
  • Tutorials
  • CSS
  • Resources
  • Tools
  • UX
  • More
    • Mobile
    • Usability
    • HTML5
    • Business
    • Freebies
    • Giveaway
    • About SpyreStudios
    • Advertise On SpyreStudios
    • Get In Touch With Us

Building a Live Textarea Character Count Limit with CSS3 and jQuery

October 18, 2012 by Jake Rocheleau

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 Demo – Download 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 Demo – Download 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.

Filed Under: Tutorial Tagged With: css, forms, html5, input, javascript, tutorials

Recent Posts

  • 31 Fresh Design Elements for Spring and Easter
  • 10 Templates for Music Concert Flyers
  • How to Build a Web Scraper Using Node.js
  • Best PHP Books, Courses and Tutorials in 2022
  • How to Get Your First Web Design Client

Archives

  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021
  • May 2021
  • April 2021
  • March 2021
  • February 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
  • April 2020
  • March 2020
  • February 2020
  • January 2020
  • December 2019
  • November 2019
  • October 2019
  • September 2019
  • August 2019
  • July 2019
  • June 2019
  • May 2019
  • April 2019
  • March 2019
  • February 2019
  • January 2019
  • December 2018
  • November 2018
  • October 2018
  • September 2018
  • August 2018
  • July 2018
  • June 2018
  • May 2018
  • April 2018
  • March 2018
  • February 2018
  • January 2018
  • December 2017
  • November 2017
  • October 2017
  • September 2017
  • August 2017
  • July 2017
  • June 2017
  • May 2017
  • April 2017
  • March 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
  • October 2016
  • September 2016
  • August 2016
  • July 2016
  • June 2016
  • May 2016
  • April 2016
  • March 2016
  • February 2016
  • January 2016
  • December 2015
  • November 2015
  • October 2015
  • September 2015
  • August 2015
  • July 2015
  • June 2015
  • May 2015
  • April 2015
  • March 2015
  • February 2015
  • January 2015
  • December 2014
  • November 2014
  • October 2014
  • September 2014
  • August 2014
  • July 2014
  • June 2014
  • May 2014
  • April 2014
  • March 2014
  • February 2014
  • January 2014
  • December 2013
  • November 2013
  • October 2013
  • September 2013
  • August 2013
  • July 2013
  • June 2013
  • May 2013
  • April 2013
  • March 2013
  • February 2013
  • January 2013
  • December 2012
  • November 2012
  • October 2012
  • September 2012
  • August 2012
  • July 2012
  • June 2012
  • May 2012
  • April 2012
  • March 2012
  • February 2012
  • January 2012
  • December 2011
  • November 2011
  • October 2011
  • September 2011
  • August 2011
  • July 2011
  • June 2011
  • May 2011
  • April 2011
  • March 2011
  • February 2011
  • January 2011
  • December 2010
  • November 2010
  • October 2010
  • September 2010
  • August 2010
  • July 2010
  • June 2010
  • May 2010
  • April 2010
  • March 2010
  • February 2010
  • January 2010
  • December 2009
  • November 2009
  • October 2009
  • September 2009
  • August 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009
  • January 2009
  • December 2008
  • November 2008
  • October 2008
  • May 2008
  • April 2008

Categories

  • Accessibility
  • Android
  • Apps
  • Art
  • Article
  • Blogging
  • Books
  • Bootstrap
  • Business
  • CSS
  • Design
  • Development
  • Ecommerce
  • Fireworks
  • Flash
  • Freebies
  • Freelance
  • General
  • Giveaway
  • Graphic Design
  • HTML5
  • Icons
  • Illustrator
  • InDesign
  • Infographics
  • Inspirational
  • Interview
  • Jobs
  • jQuery
  • Learning
  • Logos
  • Matrix
  • Minimalism
  • Mobile
  • Motion Graphics
  • Music
  • News
  • Photoshop
  • PHP
  • Promoted
  • Rails
  • Resources
  • Showcase
  • Tools
  • Tutorial
  • Twitter
  • Typography
  • Uncategorized
  • Usability
  • UX
  • Wallpapers
  • Wireframing
  • WordPress
  • Work

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

SpyreStudios © 2022