I am trying to make this contenteditable div behave like Twitter's text area. The goal is to be able to highlight characters entered beyond the character limit (as twitter does), which turned out impossible using a <textarea> as I learned that you can't select a slice of the text and format it (please feel free to correct me if I'm wrong).
That said, I know questions like this have been asked before but my problem, as I work toward that larger area, is very specific. I have the following code:
<div id="myTextArea" class="" contenteditable="true">
<span id="textAreaContent">enter text here...</span>
<div id="charCountWrapper">
<span id="charCounter"></span>
</div>
</div>
jQuery code to make this do what I need it to do:
var maxCharacters = 50;
$('#charCounter').text(maxCharacters);
$('#myTextArea').bind('input', function(){
var charCount = $('#charCounter');
var currentStr = $('#textAreaContent').text();
var newlines = $($(this).html()).length;
var currentStrLength = currentStr.length;
console.log(currentStr);
if (!!newlines) newlines -= 1;
currentStr += newlines;
if (currentStrLength > (maxCharacters - 11))
charCount.addClass('over');
else
charCount.removeClass('over');
charCount.text(maxCharacters - currentStrLength);
if(currentStrLength == 0) {
var node = document.createElement("span"); // Create a <span> node
node.setAttribute("id","textAreaContent");
var textnode = document.createTextNode(""); // Create a text node
node.appendChild(textnode); // Append the text to <li>
document.getElementById("myTextArea").appendChild(node);
}
});
When I delete the last character from the <span>, the tag is automatically removed and my counter stops working. I tried manually adding a new <span> to replace the old one, but that hasn't worked either. How can I fix this such that when I delete the last character, the count is 0, and once I start adding characters again, the counter works properly.
When I'm at the last character:
Once I delete the last character:


