How do I resize a multiline text form field in height when overflown?

Q: How do I resize a multiline text form field in height when overflown?

ℹ️ Note: This requires the Form Designer component. The below snippet can also be adapted to your needs to resize other form fields.

A: This snippet will make multiline text widgets autogrow in height when overflown:

instance.contentDocument.addEventListener("input", async function(event) {
  if (event.target.nodeName === "TEXTAREA") {
    const textInput = event.target;
    const id = textInput.parentNode.dataset.annotationId;
    const pageIndex = instance.viewState.currentPageIndex;
    const annotations = await instance.getAnnotations(pageIndex);
    const widget = annotations.find(annotation => annotation.id === id);
    if (
      widget &&
      typeof widget.fontSize === "number" &&
      textInput.scrollHeight > textInput.clientHeight
    ) {
      while (textInput.scrollHeight > textInput.clientHeight) {
        await instance.update(
          widget.set(
            "boundingBox",
            widget.boundingBox.set(
              "height",
              widget.boundingBox.height + widget.fontSize
            )
          )
        );
        // This is needed so the widget height change is propagated to the DOM
        // before the next check, otherwise we may incur in an endless loop.
        await new Promise(requestAnimationFrame);
      }
    }
  }
});

Important notes:

  • It only works for text widgets with a fixed number fontSize value (not “auto”).

  • It only works for text widgets with a doNotScroll value of false.

  • It will not change the layout of any other widgets, which will likely either overlap the text widget or be covered by it (you can add such logic yourself if necessary).

  • It will not prevent the widget from growing down the bottom bound of the page (you can add such logic yourself if necessary).

Tested in PSPDFKit for Web 2021.3.0.