The cleanest auto resize for a textarea
By Anatoly Mironov
The cleanest way to auto-resize a textarea while typing (like wall post on Facebook) is George Papadakis solution. It uses only standard javascript and provides eventlisteners for IE (attachEvent) and other browsers (addEventListener): [sourcecode language=“javascript”] window.onload = function() { var t = document.getElementsByTagName(’textarea’)[0]; var offset= !window.opera ? (t.offsetHeight - t.clientHeight) : (t.offsetHeight + parseInt(window.getComputedStyle(t, null).getPropertyValue(‘border-top-width’))) ; var resize = function(t) { t.style.height = ‘auto’; t.style.height = (t.scrollHeight + offset ) + ‘px’; } t.addEventListener && t.addEventListener(‘input’, function(event) { resize(t); }); t[‘attachEvent’] && t.attachEvent(‘onkeyup’, function() { resize(t); }); } [/sourcecode] Other solutions are <a href=“https://github.com/padolsey/jQuery.fn.autoResize/blob/master/jquery.autoresize.js, jQuery.autogrow, elastic
Comments from Wordpress.com
Anatoly Mironov - Jan 1, 2013
Thanks Martin for your response! Of course, you can use this code even if there are many texteareas. You must use an appropriate selector. The code I showed was for the demonstration only.
Not bad, but what about autoresizing for given data, i.e. a script reads different settings from a file and puts it in textareas, so that the user can edit these data. The above script autoresizes only when typing…
Thanks svasti! It is a good idea to make it to autoresize for given data. Unfortunately I don’t have time to experiment with it right now. I would appreciate if you leave a message when you find a solution for that.
Excellent sollution. But to use it if there are more textareas on one page?
Excellent solution thank u
you type additional function: var txtAreaNumber = 0; function getID(thisID) { txtAreaNumber = thisID; return txtAreaNumber; } and modify: var t = document.getElementsByTagName(’textarea’)[txtAreaNumber]; html: my function isnt on win.onload but is on click! yo good bye
Thanks for sharing!
This actually works. Getting rid of JQuery and needed an non jquery solution. Thanks for this.
Excellent.:) Thanks
Thanks for the feedback. Glad to hear that it worked for you.
Thank you it works perfectly! :D
Excellent. Worked for me at 20-Mar-2014 in latest FireFox. Thank you. So nice and clean. : )
I think this website filtering your html code. can you please email me your complete code or create a fiddle and share it here?
Thank you for sharing, Diogo!
Nice code! Just “converted” it to jQuery, since I’m already using it in my project. Here is my result: $(function() { var t = $("#message”); t.bind(‘input’, function() { t.css(“height”, ‘auto’); t.css(“height”, t[0].scrollHeight + ‘px’); }); }); I don’t know if it will work on every browser, as I just tested it on latest version of Chrome, Firefox and Opera, all on Linux.
Forgot to share a jsfiddle link: http://jsfiddle.net/LT7vW/