Split the string into chars to animate it one by one

Split the string(div) into char(span) using JS to animate it one by one.

 Yogesh    01 Dec, 2020    852

IMG: Split the string into chars to animate it one by one

In this tutorial we will split/convert the string into chars and apply the required attributes(data attribute) that will use to animate chars one by one. Input We have our div(string) tab as Input and we will convert it into set of span(char).

<h2>Hello World!</h2>

Output

<h2>
  <span style="--dealy: 0.10s" data-char="D">D</span>
  <span style="--dealy: 0.20s" data-char="e">e</span>
  <span style="--dealy: 0.30s" data-char="s">s</span>
  <span style="--dealy: 0.40s" data-char="i">i</span>
  <span style="--dealy: 0.50s" data-char="g">g</span>
  <span style="--dealy: 0.60s" data-char="n">n</span> 
  <span style="--dealy: 0.80s" data-char="D">D</span>
  <span style="--dealy: 0.90s" data-char="r">r</span>
  <span style="--dealy: 1.00s" data-char="a">a</span>
  <span style="--dealy: 1.10s" data-char="s">s</span>
  <span style="--dealy: 1.20s" data-char="t">t</span>
  <span style="--dealy: 1.30s" data-char="i">i</span>
  <span style="--dealy: 1.40s" data-char="c">c</span>
  <span style="--dealy: 1.50s" data-char="!">!</span>
</h2>    

Next, get the string content and convert it into spa(char) using javascript.

let str = document.querySelector('h2');
let title = str.innerText.split('');
let span = '';
let delay = .1;
title.forEach(char => {
  if(char == '\n' ) {
    span += '<div class="clearfix"></div>';
  } else if( char == ' ' ) {
    span +=' ';
  }
  else {
    span += '<span style="--dealy: '+(delay.toFixed(2))+'s" data-char="'+char+'">'+char+'</span>';
  }
  delay += .1;
});
str.innerHTML = span;

Explaination:

  • In the above code snippet first, we have fetched the element using the document.querySelector.
  • Next, we've split the string with space and converted it into an array of chars.
  • Then iterate every element of an array and create the text node span and assign the delay & data-char attribute to it and append it into the span var.
  • Last, replace the text/HTML content of the h2 tag with the result.