Created
September 18, 2023 15:42
-
-
Save stoph/1fa9d20cf34fdab87e6d6667f1d3e5d0 to your computer and use it in GitHub Desktop.
Expandable Textarea
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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