in this tutorial, i'll show you how to create a textarea component that satisfies these requirements:
- auto-expands as the user types (ie. growing in height).
- is accessible.
- works with “textwithnowhitespaceinbetweenlikethisone”.
- works with any font.
the solution i'm proposing does not require any extra javascript library. keep in mind the constraints above as we go through this together.
the idea
the idea is that we would like to calculate the final height of the textarea as the user types in each keystroke. here is an illustration:
there's a few things to pay attention to here:
essential values
as noted in the code comment, some css values are going to be used in javascript so that we can calculate the final height of the textarea. these values are:
- line height
- top and bottom paddings
- top and/or bottom border width
.
box-sizing
for this to work, we need to set box-sizing to border-box.
rows attribute
notice that i've set the rows attribute of the textarea to 1. this resets the
then, let's query the textarea element and add an event listener to it. this will allow us to detect the input event as the user types into the textarea.
we don't want our textarea to be resizable, since by the end of this tutorial, we would have an auto-resize textarea. so let's set its resize css attribute to none in javascript.
.
and it is working as expected.
and we can set the calculated height value back to textarea.
it seems to work fine. but what happens if we delete our text and the number of lines reduces?
, it's used to determine the minimum height required to fit all the content within the textarea withour scrollbar. hence, it will not decrease since it is assuming that the previous content we entered is the minimum amount of content.
we can fix this behaviour by setting the height property of the textarea to auto on each keystroke. this ensures that the height is reset before the calculated final height is applied to the text box.
thank you for reading!
wlto
SOCIAL SHARE CARD GENERATOR