A typical <textarea>
input tag typically looks something like this:
<textarea id="editorInput" rows="1" placeholder="Write your markdown here"></textarea>
We can set the default number of rows by specifying the rows
attribute and giving it a number.
This is fine if you're ok with a fixed size, however in my case I needed to dynamically increase and decrease the height as the user enters text.
Here's my solution:
// Get a reference to the textarea element
var editorStyle = document.getElementById("editorStyle");
// Add an event listener to trigger a callback on keyup
editorInput.addEventListener("keyup", function (e) {
// Set the rows attribute of the textarea to the current number of lines of text
// This is done by splitting the current value on newline characters and getting the length of the array
this.rows = this.value.split("\n").length;
})
The textarea height will now grow and shrink as text is broken and new lines are entered.
Last modified
·
31 Jul 2019
Did you find this article useful?