Today I Learned - Rocky Kev

TIL how to set up autogrowing textarea fields

POSTED ON:

TAGS:

Textarea Inputs tend to have a very specific height by default.

You can increase the size using a few tricks.

The MDN uses rows/cols in their example.

<textarea id="story" name="story"
rows="5" cols="33">

It was a dark and stormy night...
</textarea>

You can also increase it using a height attribute.

The MAJOR problems with the two tricks above is that it's a defined height/hardcoded height. If a end user goes beyond the height, scroll bars will appear.

What if it autogrows with typing?

I am really digging this method:


<style>
.autogrow {
display: grid;
}

.autogrow::after {
content: attr(data-replicated-value) " ";
white-space: pre-wrap;
visibility: hidden;
}

.autogrow > textarea {
resize: none;
}

.autogrow > textarea,
.autogrow::after
{
/* Add textarea styles here so that the textarea and div look the same */
grid-area: 1 / 1 / 2 / 2;
}
</style>

<label for="content">Type something</label>
<div class="autogrow">
<textarea id="content" onInput="this.parentNode.setAttribute('data-replicated-value', this.value)"></textarea>
</div>

It uses a wrapper element, CSS grid, and a sprinkling of vanilla JS, and it works wonderfully! But… if your textarea has text in it when the page loads, it doesn’t work.

Add this snippet in there that runs after page load and it'l handle that!

function setAutogrow () {
let autogrow = document.querySelectorAll('.autogrow');
for (let field of autogrow) {
if (!field.value) continue;
field.setAttribute('data-replicated-value', field.value);
}
}

via How to automatically size a textarea based on its using vanilla JavaScript


Related TILs

Tagged:

TIL another way to prevent buttons from submitting HTML

When you have two buttons, you can use 'type=button' to stop them from submitting a form.

TIL how to set up autogrowing textarea fields

There's some css tricks to autogrow textarea. There's also a nice piece of JS to use to do it as well!

TIL you can wire different inputs to different forms

You can add the form element inside a input, to point specifically to the form you want to target.