Textarea Self-Growing Video Tutorial
In this new video where I suggest you discover how to create a textarea that grows automatically. The objective is to ensure that when the user types text that exceeds the display area, the textarea grows rather than triggering the display of a scrollbar.
Custom element
To create this element we will use the API CustomElement which will allow to apply the behavior automatically to all HTML elements having the attribute is = "textarea-autogrow"
.
The main problem we will encounter is the calculation of the height of the text that has been entered by the user. For this we will base ourselves on the property scrollHeight
(this property allows you to obtain the actual height of a scrollable element). Once this value is obtained, it is enough to transfer it to the level of the textarea style. This makes it easy to cover the case where the text box needs to grow.
this.style.height = this.scrollHeight + 'px'
However, this does not manage the case where the user deletes content.
Indeed, the text area having grown following the previous operation, the calculation of the scrollHeight
will then be distorted. To remedy this problem, simply ask the browser to reset the height of the element before asking it for the height of the text box.
this.style.height = 'auto'
this.style.height = this.scrollHeight + 'px'
So much for the key principle of resizing our text area. Obviously we will now have to implement this behavior during the various interactions that the user can have with our text area.
First, we will only do this when the user focuses the field. There is no point in making calculations until the user interacts with the text box. Then, we will also have to manage the case of resizing. Once the user has interacted with the text zone, and the height has adapted to the content, the resizing of the page must entail a calculation of the height. We will be extremely careful to use a function that does not permanently re-launch this resizing.
Finally, it will be necessary to foresee the case where the textarea is removed from the page and remove the various event listeners that may have been initialized during the creation of the element.