Skip to content

Instantly share code, notes, and snippets.

@stoph
Created September 18, 2023 15:42
Show Gist options
  • Save stoph/1fa9d20cf34fdab87e6d6667f1d3e5d0 to your computer and use it in GitHub Desktop.
Save stoph/1fa9d20cf34fdab87e6d6667f1d3e5d0 to your computer and use it in GitHub Desktop.
Expandable Textarea
/**
* Expands a textarea element to fit its content up to a maximum height.
* @param {string} id - The id of the textarea element.
* @param {number} [maxHeight=0] - The maximum height of the textarea element. 0 for no maximum.
* @author Christoph Khouri <christoph.khouri@gmail.com>
*/
function expandableTextarea(id, maxHeight = 0) {
const textarea = document.getElementById(id);
textarea.style.height = 'auto';
textarea.style.height = (textarea.scrollHeight) + 'px';
textarea.addEventListener('input', function () {
if (maxHeight == 0 || this.scrollHeight <= maxHeight) {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
} else {
this.style.height = 'auto';
this.style.height = maxHeight + 'px';
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment