Auto-Adjust Textarea in LabArchives Widgets
How to make textareas grow or shrink with text entry
This article is part of a series on how to get started with designing custom LabArchives Widgets. You can find the introduction and links to the other articles in the series here.
You can find the code to implement these textareas in my GitHub repository https://github.com/gibson-amandag/LabArchivesWidgetTemplates/tree/main/_commonComponents/autoAdjustTextarea
When adding a textarea to your widget, it’s often nice to have the textarea grow and shrink as the content within it changes, rather than relying on a fixed number of rows and the scroll bar. In this article, I provide an example to achieve this behavior.
To implement this solution, you must add autoAdjust
as a class to the textarea
within the HTML script. Within my setUpInitialState
method, for each textarea
with the class of autoAdjust
, I get the scrollHeight
of the textarea
element, which is the length from the top to the bottom of the text itself.
If the textbox is hidden at the time this initialization is completed, its height is 0, and it has to be handled separately. Your HTML form should have a <div>
with the class of forTextBox
. I temporarily show this <div>
and then copy the text from the existing textarea into the forSizing
temporary textarea. The function uses the scrollHeight
of this temporary textarea to update the height
value, and then re-hides the forTextBox
<div>
. Finally, the function uses setAttribute
method to update the height of the textbox to the calculated height
value.
When input is added to the textarea (.on("input", (e)=>{})
), the style height is updated again with the scrollHeight
of the textarea. The entire widget has to also be resized, as there is no scroll bar for widgets added to a LabArchives page. I create my own resize
function which at minimum calls the LabArchives resize_container
method.
If any other interactions with the form alter the display of textareas, I also call the updateTextarea
method, which updates non-hidden textareas. I implement this by adding a checkText
class to these elements.