Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!