1

I have a textarea .txt which has a limit of 250 char.

I want the background of text getting red if reached >250 char. Just like twitter. But i dont wanna use contenteditable div as used by twitter for many reasons.

$('.txt').keyup(function{
  if($(this).val().length>250){
  //limit reached now change bg of >250 chars.
}});

I only want to change the background of text after 250 characters & not the whole textarea.

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
HackerManiac
  • 243
  • 1
  • 4
  • 20

1 Answers1

1

You can wrap the "user inserted text" in a element span class="classError" with the style you want, such as:

$(document).ready(function(){

  var max_length = 25;

  $("#editable").on("keyup", function(){


    if( $(this).text().length > max_length){

      $(this).css("color", "red");

      $("#editable").html('<span class="error">' + $("#editable").text() + '</span>');


    } else {

      $(this).css("color", "");     

    }

  });

});
  • you can find this example jsbin here (http://jsbin.com/nehac/1/) it's just the basic concept needs improvement, but I'm pretty sure you can do the rest!

You'll then have to solve the cursor position, there's a few solutions, like this one (How to move cursor to end of contenteditable entity)

Hope this helps!

Community
  • 1
  • 1
punkbit
  • 7,347
  • 10
  • 55
  • 89