I want to create a text box that selects the text outside the character (for example, twitter).
My attempt here: http://jsfiddle.net/X7d8H/1/
HTML
<div class="wrapper"> <div class="highlighter" id="overflowText"></div> <textarea id="textarea1" maxlength="200"></textarea> </div> <div id="counter">Letters remaining: 140</div> <input type="Button" value="Done" id="doneButton"></input>
CSS
* { font-family: sans-serif; font-size: 10pt; font-weight: normal; } .wrapper { position: relative; width: 400px; height: 100px; } .wrapper > * { position: absolute; top: 0; left: 0; height: 100%; width: 100%; padding: 0; margin: 0; border: 0; overflow: hidden; resize: none; white-space: pre-wrap; white-space: -moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; word-wrap: break-word; } .highlighter { background-color: #eee; color: #f0f; } .highlight { background-color: #fd8; color: #f0f; } textarea { background-color: transparent; color:#000; }
JAVASCRIPT
function limitTextSize(e) { var max = 140 var txt = $("#textarea1").val(); var left = txt.substring(0, max); var right = txt.substring(max); var html = left + '<span class="highlight">' + right + "</span>"; $("#overflowText").html(html); $("#counter").html("Letters remaining: " + (max - txt.length)); $("#doneButton").attr("disabled", txt.length > max); } function maxLength(el) { if (!('maxLength' in el)) { var max = el.attributes.maxLength.value; el.onkeypress = function () { if (this.value.length >= max) return false; }; } } $(document).ready(function() { $("#textarea1").bind('input propertychange', limitTextSize) maxLength($("#textarea1")); });
It uses jQuery
It works except firefox. To see the error, paste it into the text box:
fjdf hkj hfj hdfkjsd hfllll sdfl sdlflldsf lsdlf flsdlf lsdf lsdf llsdfls dlfs ldflsd f
which reveals a slight formatting difference between div and textarea (firefox only). I made the โhiddenโ text purple so you can see the word wrap.
I looked here: How do I get Firefox to display textarea debugging just like in a div?
And here: Wrapping text in the same way in a div as in a text field
And here: Fixed a bug in the size of the text area of โโFirefox
But none of them fit ...
I was thinking of trying to make its content accessible div, but getting change events looks like a minefield.
Has anyone here done this successfully?