Berat Şen Berat Şen - 3 months ago 21
Javascript Question

How can I make a textarea with character limit highlighting like Twitter?

Twitter's submit tweet textbox highlights the characters that are over the character limit:



As you can see, the characters that overrun the character limit are highlighted in red. How can I achieve something like this?

Answer

You'll find the necessary solution and required code here:

How to insert <em> tag when exceeding 140 limit i.e. going negative?

...and here:

REGEX - Highlight part over 19 chars

Your question appears to be duplicitous.

Note: I didn't have the option to post the above links as a comment (i.e. privilege contingent on reputation).

Here's the code as per Simon Kuang's recommendation (see comments):

HTML:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <h3>Your text here</h3>
   <div contenteditable="true" id="myDiv">edit me
  </div>
  <p>
    <h3>Stuff over 19 characters</h3>
  <div id="extra">
  </div>
  <p>
    <h3>Sample output</h3>
    <div id="sample">

  </div>
</body>
</html>

CSS:

.highlight {
 color:red;
}

JavaScript:

$(document).ready(function() {
  $('#myDiv').keyup(function() {
    var content = $('#myDiv').html();
    var extra = content.match(/.{19}(.*)/)[1];

    $('#extra').html(extra);

    var newContent = content.replace(extra, "<span class='highlight'>" + extra + "</span>");
    $('#sample').html(newContent);
  });
});