The following code dynamically sets the rows attribute of a textarea element to the number of lines in the textarea’s value. It works vey much like the old autosize plugin but it can be accomplished with very little code using Alpine JS.
Note: you must have the core Alpine installed for this to work.
<form x-data="{ textareaContent: '', textareaRows() { return (this.textareaContent.match(/\n/g)?.length ?? 0) + 1 } }">
<!-- Rest of the form -->
<textarea name="message" :rows="textareaRows()" columns="25" placeholder="Press enter/backspace and it will add/remove more rows" x-model="textareaContent"></textarea>
<!-- Rest of the form -->
</form>
Tim Bennett is a freelance web designer from Leeds. He has a First Class Honours degree in Computing from
Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.