autosize-input
autosize-input copied to clipboard
:balloon: Effortless, dynamic-width text boxes in vanilla JavaScript
autosize-input

Effortless, dynamic-width text boxes in vanilla JavaScript.
- Dynamically adjusts the width of the text box to fit its current contents
- Can be initialised to fit its
placeholderattribute - Optionally set a
min-widthbased on the element’s initial content - 718 bytes gzipped
Usage
<input type="text" id="foo" value="Nice">
<input type="text" id="bar" placeholder="People">
<input type="text" id="baz" placeholder="Matter">
const autosizeInput = require('autosize-input')
autosizeInput(document.querySelector('#foo'))
autosizeInput(document.querySelector('#bar'))
autosizeInput(document.querySelector('#baz'), { minWidth: true })
API
const autosizeInput = require('autosize-input')
autosizeInput(element [, options])
element is a text input element, and options is an object literal.
- Returns a “clean up” function for removing the event listener on the
element. - If we do not want the text box to “contract” as the user starts to type, set
options.minWidthtotrue. This will give theelementamin-widththat fits it initial contents (ie. either the element’s intialvalue, or itsplaceholder).
See Usage.
Implementation details
- A hidden “ghost”
divelement, assigned the same styles as the text box, is used to calculate the correct width to assign to the text box. This width is recomputed and assigned to the text box on everyinputevent. - The single “ghost”
divis shared amongst all the “autosized” text boxes on the page.
Installation
Install via yarn:
$ yarn add autosize-input
Or npm:
$ npm install --save autosize-input
Tests
To test manually, in the browser:
$ yarn start
To run the programmatic tests:
$ yarn test
Prior art
This module was written because I needed a standalone, lightweight solution to this rather UI problem.
License
MIT