I have a content editable div and I wrote a custom function to get the character count which is as below:
var charCount = function (elem, event) {
var charBox = elem.find('.maxLengthCount'),
txtBox = elem.find('textarea'),
rte = elem.find('.textareaEditBox'),
maxLength = parseInt(txtBox.attr('maxLength'));
if(!rte.hasClass('placeholderText')) {
/* This is where the remaining characters are being counted */
var remainingChars = maxLength - rte.prop('innerHTML').length;
charBox.html(remainingChars);
if (remainingChars < 0) {
charBox.parent('div').addClass('fntRed');
rte.addClass('borderRed');
txtBox.addClass('error');
} else {
charBox.parent('div').removeClass('fntRed');
rte.removeClass('borderRed');
txtBox.removeClass('error');
}
} else {
charBox.html(maxLength);
}
}
charCount(wrapper, null);
editor.on('keyup', function(event) {
charCount($(this).closest('.field-wrapper'), event);
});
ISSUE: Everytime I press < or > the char count reduces by 4, everytime I press space bar the char count reduces by 6
When you are editing the content of the contenteditable elements some characters get transformed in their html escapes:
You will have to replace these characters with their original value to count correctly the number of characters in the text. Why don't you use a textarea for this purpose? With contenteditable elements you will get in more troubles like pasting images or links, textareas are just for texts and do not escape the characters like in your case.