Today I was messing around with my admin side of things and I discovered that my textareas were not behaving the way I wanted them to. I want them to grow when you type into them. I had this complicated code written out to accomplish this, but I thought, "there's gotta be a better way." So here's my code.
- <textarea></textarea>
- <script>
- $('textarea').each(function(){
- var that = $(this);
- that.css('box-sizing','border-box'); //-> required to get the correct height of input
- function resizeInput(){ //-> create function so I can place it in many different locations
- that.stop(true,true).animate({
- 'min-height':that.get(0).scrollHeight
- });
- }
- resizeInput(); //-> resize on page load
- that.off('keydown').on('keydown',function(){ //-> resize when you type, keydown is efficient
- resizeInput();
- });
- });
- </script>
I want this to apply to every single textarea that's on my pages. For some reason you have to make sure that the 'box-sizing' attribute is set to 'border-box'. Instead of checking first, I'll just set the attribute so there's no confusion in the future. Then you set the height to the scroll height you find using jQuery. I set the min-height to that so I can still resize the box bigger if I want to. This might be personal preference, but sometimes while I work in a textarea I like to give myself extra room to type things. Setting the min-height to the scroll height will allow me to make it bigger if I choose to.
I use the animate function so that it looks a little nicer, but you can use .css({}); if you want it to happen quicker.
-
Recent Blog Posts
- 4/5 [PhpMyAdmin] Incorrect Format Parameter (Database Import Issue)
- 4/3 [CentOS] How To Check Current Version Of Apache
- 4/3 [Terminal] How To Fix Warning About ECDSA Host Key
- 4/2 [CentOS 8] How To Set Up New Server From A Blank Slate
- 3/25 How I Improved First Contentful Paint And First Meaningful Paint