Is there anyway through CSS or Javascript set the height of the textarea based on the content? I have a hardcoded height in my CSS but i wanted it to default so there is no vertical scroll bar on page load?
相关问题
- Views base64 encoded blob in HTML with PHP
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
A nice solution
JSFiddle
HTML
CSS
JQuery
Tested in chrome
Pure javascript solution (No plugin, No jquery)
in action: fiddle
I created 3 functions:
I couldn't use
scrollHeight
as it return 0 on page load (maybe because my textarea is hidden on load). Probably not nest practice (I am a newby in js) but the only option that worked was to count the number of lines intextarea
and get length of the longer line in it. Then set thewidth
andheight
accordingly.If needed, you can also set
max-width
(ormax-height
) like thisI don't know why, but it seems my search engine brought me another solution (a "How-To" Tutorial):
http://www.sitepoint.com/build-auto-expanding-textarea-3/
EDIT:
here is the code..
I left the comments in the code since it is not my work ;)
If you dont mind a scollbar inside the text area you can use
and here is a Fiddle
another Fiddle this has min and max-width set.
but with plug-ins like auto-size
the height of the text box increases with input.
or you can try this plug-in
The only css I use below on the
textarea
is itswidth
, there is no need to set an initialheight
.overflow
should not be needed either as thescrollHeight
that will be used is:scrollHeight :MDN
If you want to work with Internet Explorer though, then it is necessary to use
overflow: auto
as otherwise IE insists on adding a vertical scrollbar (even though there is nothing to scroll).Note that the
width
does not need to be specified either, but it is the property that is most commonly set in relation to this topic.This is the JavaScript needed:
When the DOM has loaded the
height
of the textarea is set to itsscrollHeight
.Here is a complete page for testing:
If required, the code can be applied to all textareas on the page: