Stagger Split Text Animation With Vanilla JS

Wrap your header element with div and set class name as “.split-text”. Set header class name as “.split-text__header”. Inset code block element and copy and paste below to code block and execute it.

Example:

Lorem ipsum dolor sit amet, consectetur adipiscing elit

<style> 
  h1 span{
  margin-right: 1.2rem;
}
  .split-text span {
  display: inline-block;
  opacity: 0;
  transform: translatex(100px);
  transition: opacity 0.5s ease-out, transform 0.5s ease-out;
}
</style>

<script>
  // Get the heading element
const heading = document.querySelector('.split-text .split-text__heading');

// Split the text into individual words
const words = heading.textContent.split(' ');

// Replace the original text with the split words
heading.innerHTML = '';

words.forEach(word => {
  const span = document.createElement('span');
  span.textContent = word + ' ';
  heading.appendChild(span);
});

// Animate each word with a staggered delay
const animateWords = () => {
  const spans = heading.querySelectorAll('span');

  spans.forEach((span, index) => {
    setTimeout(() => {
      span.style.opacity = 1;
      span.style.transform = 'translatex(0)';
    }, index * 100 + 500);
  });
};

// Call the animation function
animateWords();

</script>

Leave comment or code correction