This code will make the overflowing characters red. I use text()
because this ignores the em
tag within the div.
$(function () {
$('div').keyup(function () {
var $this = $(this),
text = $this.text(),
maxlength = 20;
if (text.length > maxlength) {
var first = text.substring(0, maxlength),
overflow = text.substring(maxlength, text.length);
// this.innerHTML = first + '<em>' + overflow + '</em>';
$this.text(first);
// Now all there's left to do is force the caret at the end,
// but that's pretty much code and would make this messy.
// I'm sure you can google this. There's a link in my answer.
}
});
});
With this HTML
<div contenteditable="true" spellcheck="true" role="textbox" aria-multiline="true" id="342387257900146688">
Type here.
</div>
Here's a live fiddle: http://jsfiddle.net/BaN7D/1/
However, if it exceeds the max length, .html()
will force the cursor at the beginning. There are samples out there to place a cursor at the end of the div. Here's someone on SO that asked a question about it with a good answer: Set cursor position on contentEditable <div>