How do you get text responsive when all the letters have a <span> around them?

125 Views Asked by At

So what to be able to put any text in <h2> without it going like this:

some random text for the anim
ation

but more like this:

some random text for the
animation

(function() {
  // Wrap every letter in a span
  var textWrapper = document.querySelector('.ml');
  textWrapper.innerHTML = textWrapper.textContent.replace(/\S/g, "<span class='letter'>$&</span>");

  anime.timeline({
      loop: false
    })
    .add({
      targets: '.ml .letter',
      translateX: [40, 0],
      translateZ: 0,
      opacity: [0, 1],
      easing: "easeOutExpo",
      duration: 2000,
      delay: (el, i) => 200 + 10 * i
    }).add({
      targets: '.ml .letter',
      // translateX: [0,-30],
      // opacity: [1,0],
      easing: "easeInExpo",
      duration: 1100,
      delay: (el, i) => 100 + 30 * i
    });
})();
.ml {
  overflow: hidden;
}

.ml .letter {
  display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script>
<h2 class="ml">some random text for the animation</h2>

1

There are 1 best solutions below

0
On BEST ANSWER

You could try wrapping a div around each word then it wouldn't break at each letter

const words = textWrapper.innerText.split(' ');
textWrapper.innerHTML = ""


words.forEach(word => {
    textWrapper.innerHTML += `<div style="display: inline-block"> 
         ${word.replace(/\S/g, "<span class='letter'>$&</span>")}
    </div>`
})