textarea-autoresize
This package provides a function, that, given textarea
DOM Element and (optionally) a set of options,
calculates it's height
and overflow-y
for the size of it's content.
Key points
- Browser support: IE10+
- Written in pure Javscript(ES6+), framework-agnostic
- It DOES NOT use ghost elements to calculate the style, so there are no bugs due to the styles mismatch.
- There are helpful errors and warnings for non-production environment (sanity checks)
The calculation takes into account every possible combination of:
height
of the content inside the textarea(including placeholder)maxRows
(if passed in options) andmax-height
in CSS(if present), whichever is smallerminRows
(if passed in options),rows
attribute ontextarea
element(if present) andmin-height
in CSS(if present), whichever is biggerbox-sizing
padding-top
andpadding-bottom
border-top
andborder-bottom
Installation
npm install --save textarea-autoresize
Usage:
import { getTextareaStyle } from 'textarea-autoresize';
// Default options
const options = {
minRows: 0,
maxRows: Infinity,
canShrink: true
};
const { height, overflowY } = getTextareaStyle(textarea, options);
textarea.style.height = height;
textarea.style.overflowY = overflowY;
Methods
getTextareaStyle(textarea[, options])
-
Description:
- Calculates
height
andoverflow-y
fortextarea
element to match the height of it's content, includingpadding
andborder
.
- Calculates
-
Arguments:
- textarea:
- Type:
Element
- Description: Textarea DOM Node
- Type:
- options (optional):
- Type:
Object
- Properties:
- minRows (optional):
- Type:
Number
- Description: minimum amount of rows allowed, expected to be an integer >= 0
- Default:
0
- Type:
- maxRows (optional):
- Type:
Number
- Description: maximum amount of rows allowed, expected to be an integer >= minRows
- Default:
Infinity
- Type:
- canShrink (optional):
- Type
Boolean
- Description: whether textarea is allowed to shrink in height(or only expand)
- Default:
true
- Type
- minRows (optional):
- Type:
- textarea:
-
Return value:
- Type:
Object
- Description: new calculated style for textarea
- Properties:
- height:
- Type:
String
- Description: new textarea
height
inpx
, e.g.100px
- Type:
- overflowY:
- Type:
String
- Description: new textarea
overflow-y
value - One of:
hidden
auto
- if calculated height is bigger, than maximum allowed height
- Type:
- height:
- Type: