Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
Perform text animation by splitting text, but retain line breaks

I have created a function that maps over a sentence (provided by a CMS) and adds containers to each word. Splitting each word at spaces.

Now, some words will require line breaks, but my function is wiping them out, and I am not quite sure how I am going to retain line breaks in this case.

The demo below displays the issue I am having. The second one, although originally having a line break, has it remoed when the function runs

Any ideas or advice of how to retain the breaks will be appreciated. For the purpose of my animations, each word will require the markup in the return value of $reformatedText

let $textAreaContent;
let $splitText;
let $reformatedText;
let $delayTime;
let $delayValue;
let $textAreas = document.querySelectorAll('.stagger-text');


function setDelayValue(curCount) {
  $delayTime = 0.075;
  return parseFloat(curCount * $delayTime).toFixed(3);
}

function createStaggerContainers($textArea) {
  $textAreaContent = $textArea;
  $splitText = $textAreaContent.innerText.split(/\s|<br>/g);

  $reformatedText = $splitText.map((item, i, arr) => {
    $delayValue = setDelayValue(i);
    return `<span class="stagger__container">
              <span class="stagger__text" style="animation-delay: ${$delayValue}s">${arr.length - 1 === i ? item : `${item}&nbsp;`}</span>
            </span>`;
  }).join('');

  $textAreaContent.innerText = '';
  $textAreaContent.innerHTML = $reformatedText;
}

if ($textAreas && $textAreas.length) {
  $textAreas.forEach(($textArea) => {
    createStaggerContainers($textArea);
  });
}
<div class="stagger-text">Some text here</div>
<div class="stagger-text">This has line<br> breaks</div>

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda