Hi I am trying to limit text in contenteditable="true" div:
var char = 500;
$("#counter").append("You have <strong>" + char + "</strong> chars left.");
$("#editor").keypress(function () {
if ($(this).text().length > char) {
$(this).text($(this).text().substr(1));
}
var rest = char - $(this).text().length;
$("#counter").html("You have <strong>" + rest + "</strong> chars left.");
if (rest <= 100) {
$("#counter").css("color", "#ff7777");
}
else {
$("#counter").css("color", "#111111");
}
});
unfortunately I am facing following problems:
- When div contain any text by default, the number of chars left is not being updated until any insertion or deletion.
- If the user exceeds the maximum number of chars, the carriage goes to the beginning of the text box and deletes the first char instead of the recently inserted one.
- If user pastes a text longer than 200 chars, it won't be shortened.
Please find the code: http://jsfiddle.net/mmacin/A69tk/1/