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:
Please find the code: http://jsfiddle.net/mmacin/A69tk/1/
Here is my go at providing a solution. It has one piece of the puzzle missing which i will complete soon.
Here is the fiddle
The counters work as desired now . What remains is if the user exceeds the limit what should be done.
If you have used twitter, you will see that they do not strip the extra chars but higlight those chars with a red selection to show the user that those chars won't be part of the tweet.Perhaps such an alternative would be better
Here is the jQuery that i used.
const limit = 200;
rem = limit - $('#editor').text().length;
$("#counter").append("You have <strong>" + rem + "</strong> chars left.");
$("#editor").on('input', function () {
var char = $('#editor').text().length;
rem = limit - char;
$("#counter").html("You have <strong>" + rem + "</strong> chars left.");
console.log(char)
console.log(rem);
if (char >= 100) {
$("#counter").css("color", "#ff7777");
}
else
$("#counter").css("color", "#111111");
if(char>200)
{
//add code to either remove extra chars or highlight them.
}
});
If you see I have used $("#editor").on('input', function ()
which will check for input's inside the textarea rather than key-press so that should take care of the user copy pasting text inside the textarea. Also I have changed the way the counters work. I'm sure you can figure out the logic yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With