Pt-br: Ajustando Automaticamente a altura dos inputs long answer no WeWeb / Automatically adjusting the height of long answer inputs on WeWeb

Pt-br: Ajustando Automaticamente a altura dos inputs long answer no WeWeb
Automatically adjusting the height of long answer inputs on WeWeb

Sempre é um desafio ajustar a altura do input tipo long answer de forma automática, pensando nisso eu criei uma solução para esse problema onde você pode ajustar a altura de todos os inputs dentro de uma div ou elemento.

It is always a challenge to adjust the height of the long answer type input automatically, with this in mind I created a solution to this problem where you can adjust the height of all inputs within a div or element.

Use the onMounted Event in the Parent Div’s Workflow

Select the Parent Div: In WeWeb, select the div that wraps all the inputs.

Access the Workflow: Go to the Workflows tab in the side panel and add a new onMounted event to the parent div.

Add Custom Code: In the onMounted event, add a block of custom JavaScript code. This code will be responsible for dynamically adjusting the height of all inputs within the div.

Code:

function adjustTextareaAutoHeight(context) {
  // Seleciona todos os elementos <textarea> no contexto atual
  const textareas = context.thisInstance.querySelectorAll('textarea');
  if (!textareas.length) return;

  textareas.forEach(textarea => {
    // Oculta a barra de rolagem e ajusta a altura para 'auto'
    textarea.style.overflow = 'hidden';
    textarea.style.height = 'auto';
    textarea.style.height = textarea.scrollHeight + 'px';

    // Adiciona o evento 'input' para ajustar a altura conforme o usuário digita
    textarea.addEventListener('input', function() {
      textarea.style.height = 'auto'; // Reseta a altura
      textarea.style.height = textarea.scrollHeight + 'px'; // Ajusta a altura
    });
  });
}

// Chama a função sempre que o elemento é montado
return adjustTextareaAutoHeight(context);

Result:

Updated version of code using MutationObserver:

function adjustTextareaAutoHeight(context) {
  // Função para ajustar a altura do <textarea>
  const adjustHeight = (textarea) => {
    textarea.style.overflow = 'hidden';
    textarea.style.height = 'auto'; // Reseta a altura
    textarea.style.height = textarea.scrollHeight + 'px'; // Ajusta a altura
  };

  // Função para configurar o evento de ajuste em cada <textarea>
  const setupTextarea = (textarea) => {
    adjustHeight(textarea); // Ajusta inicialmente
    textarea.addEventListener('input', function() {
      adjustHeight(textarea); // Ajusta conforme o usuário digita
    });
  };

  // Função para observar mudanças no DOM e ajustar novas textareas
  const observeTextareas = () => {
    // Seleciona todas as textareas no contexto atual
    const textareas = context.thisInstance.querySelectorAll('textarea');
    textareas.forEach(setupTextarea);

    // Configura o MutationObserver para monitorar mudanças no DOM
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        mutation.addedNodes.forEach((node) => {
          if (node.tagName === 'TEXTAREA') {
            setupTextarea(node); // Ajusta novas textareas adicionadas
          } else if (node.querySelectorAll) {
            // Se o node tiver textareas dentro dele, ajusta elas também
            node.querySelectorAll('textarea').forEach(setupTextarea);
          }
        });
      });
    });

    // Inicia o observer para o contexto atual
    observer.observe(context.thisInstance, {
      childList: true,
      subtree: true, // Para observar também os nós filhos
    });
  };

  // Chama a função para observar e ajustar os <textarea> existentes
  observeTextareas();
}

// Chama a função sempre que o elemento é montado
return adjustTextareaAutoHeight(context);

With this, the script adjusts the height of existing and also observes the DOM to adjust new ones that are added dynamically.

1 Like

Oi @wgsantos

Muito legal, cara! :slight_smile: