Although far from perfect, here is my attempt: http://jsfiddle.net/V6BSY/2/
I just tried to solve the problem of horizontal scaling, as many other people have already shown how vertical scaling is performed.
It also reduces the size of the container when using backspace.
HTML:
<div id="txt"> <textarea></textarea> </div>
CSS
#txt { background-color: rgba(208,228,254,0.3); border: 2px dashed #000000; height: 20px; padding: 5px; } #txt textarea { border: none; background: none; resize: none; outline: none; overflow: hidden; width: 10px; height: 15px; font-size: 10px; }
JavaScript:
$(document).ready(function() { $("#txt").css("width", $("#txt textarea").css("width")); }); $('textarea').keydown(function(e) { lines = $('#txt textarea').val().split('\n'); maxLength = getLengthOfLongestLine(lines); var h = parseInt($(this).get(0).scrollHeight) + 5; var w = maxLength * parseInt($(this).css('font-size')); if ((e.keyCode || e.which) == 13) { $("#txt").css("height", h); $(this).css("height", h); } else { $("#txt").css("width", w); $(this).css("width", w); } }); function getLengthOfLongestLine(arrLines) { var maxLength = 0; for(var line in arrLines) { if (arrLines[line].length > maxLength) { maxLength = arrLines[line].length; } } return maxLength; }
source share