Auto-expandable Textarea snippet for HTML textarea fields built with native javascript
This snippet:
- 🔥 is built with native javascript
- 📦 requires no dependencies
- ⚒️ highly customizable yet very simple
Add either unminified or minified JS onto your html
<script src="/js/textarea-expander.js"></script>
<!-- minififed -->
<script src="/js/textarea-expander.min.js"></script>
You can also use below CDN links. Feel free to change version number with respect to the releases
<script src="https://cdn.jsdelivr.net/gh/giray123/[email protected]/js/textarea-expander.js"></script>
<!-- minififed -->
<script src="https://cdn.jsdelivr.net/gh/giray123/[email protected]/js/textarea-expander.min.js"></script>
Initialize Autocomplete object with your configurations
var expander1 = new textAreaAutoExpander('#textarea_expand_both_ways')
var expander2 = new textAreaAutoExpander({
selector: '#textarea_expand_vertically',
safetyMargin: 200,
autoHeight: true,
autoWidth: false
})
var expander3 = new textAreaAutoExpander({
selector: '#textarea_expand_horizontally',
safetyMargin: 200,
autoHeight: false,
autoWidth: true
})
Auto expanding a textarea based on user input is a tedious task. However, there is a workaround which this snippet is using. When you initialize the snippet, it creates a copy div element of the textarea which is not observable on the page, it then syncs all the related CSS attributes between the textarea and the hidden element so that their width and height changes the same amount. When user types, it calculates the width/height of the hidden element and copies it to the textarea. Because of this dynamic, you can not style your textarea during expansion and expect it to continue expanding properly. You need to call expander.refresh()
after you style your textarea so that the snippet syncs CSS parameters again.
attribute | type | default | description |
---|---|---|---|
selector |
string | required | html input element query selector (document.querySelector(selector) ) |
safetyMargin |
integer | 100 |
minimum pixel distance between text and the border before expanding starts |
autoHeight |
boolean | true |
whether to expand vertically |
autoWidth |
boolean | true |
whether to expand horizontally |
attribute | description |
---|---|
state() |
returns information about the current state |
refresh() |
syncs fontFamily, whiteSpace, fontSize, lineHeight between the textarea and the hidden element. You can use expander.refresh({fontSize: 20, lineHeight: 20}) command to change fontSize and lineHeight directly with this method |
This project is licensed under the terms of the MIT license.