jQuery: How to create a textarea character countdown for Twitter

Twitter has a 280 character limit for tweets. If you need to build an input form that will remotely post tweets to Twitter, you will need to make sure that the messages are not too long. In this article I will show how to build a textarea that has a text counter attached to it which will show a countdown of how many characters you have left when crafting a Twitter message. The countdown updates in real time as you type. Here is what it looks like:

I will demonstrate how to build this in three parts.

 

Step 1: Create the HTML:  textarea, CDNs, and CSS div structure

The first step is to design the overall HTML structure. In this case, I will use a CSS grid with two columns. The text area will go in the left column, and the real-time character count will go in the right column. I created a box for these two columns which has a gray background. Here is the HTML:

<h3>Twitter allows 280 character per tweet</h3>

<div class="box">
  <textarea rows="6" cols="65" class="txtara"></textarea>
  <span id="characters">
    <div class="right-side-count">280</div>
    <div class="right-side">characters remaining</div>
  </span>
</div>

Note: For this project I am using two CDNs, one for jQuery and one for the Roboto font from Google fonts. Here is what the CDNs look like. (They should be placed in HEAD of the HTML document)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

 

Step 2: Create the CSS styling

Here is what the CSS styling looks like:

body { font-family: 'Roboto', sans-serif; }

.box {
  width: 100%;
  height: 150px;
  background-color: #ccc;
  display: grid;
  grid-template-columns: auto auto;
}

.txtara {
  margin: 20px;
  border-radius: 6px;
  border: 1px solid #888;
}

.right-side {
  width: 80px;
  margin: 0px 20px 20px 5px;
  text-align: top;
  font-family: 'Roboto', sans-serif;
  font-size: 22px;
  color: #999;
}

.right-side-count {
  width: 80px;
  margin: 30px 20px 0px 5px;
  text-align: top;
  font-family: 'Roboto', sans-serif;
  font-size: 22px;
  color: #999;
}

 

Step 3: Write the jQuery code

In the <script></script> portion of the HTML document, place the following jQuery code:

$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);

function updateCount() {
  let maxLength = 280;
  let charsEntered = $(this).val().length;
  $('.right-side-count').text(maxLength - charsEntered);
}

This code uses keyup and keydown events which call a simple function called updateCount().

Here is a codepen which demonstrates this in action:

See the Pen Twitter feed character count-down (jQuery) by Chris Nielsen (@Chris_Nielsen) on CodePen.0