Skip to content

Instantly share code, notes, and snippets.

@timc1
Created January 27, 2019 18:12
Show Gist options
  • Save timc1/244de4018bf2af0d5575cf56c5734cef to your computer and use it in GitHub Desktop.
Save timc1/244de4018bf2af0d5575cf56c5734cef to your computer and use it in GitHub Desktop.
Converts text node to an array of animated spans
const animate = (el, delay = 0) => {
const node = el.childNodes[0]
// Check first if this node is a text node
if (node.nodeType === 3) {
const text = node.data.split('')
const html = text.reduce((acc, curr, index) => {
if (curr !== ' ') {
const wait = delay * index + delay
return (acc += `<span class="animate" style="animation-delay: ${wait}ms">${curr}</span>`)
}
return (acc += `<span> </span>`)
}, '')
el.innerHTML = html
}
}
animate(document.getElementById('title'), 40)
@timc1
Copy link
Author

timc1 commented Jan 27, 2019

Preview Template

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Animate Letters</title>

    <style>
      :root {
        --ease: cubic-bezier(0.67, 0.1, 0.07, 1);
      }

      @keyframes slideInUp {
        100% {
          transform: translateY(0);
          opacity: 1;
        }
      }

      .animate {
        color: #fff;
        transform: translateY(15px);
        opacity: 0;
        display: inline-block;
        animation: slideInUp 0.4s var(--ease);
        animation-fill-mode: forwards;
      }

      body {
        background: black;
        display: grid;
        place-items: center center;
        height: 100vh;
      }
    </style>
  </head>
  <body>
    <h1 id="title">Hi my name is Tim</h1>
    <script src="animate-letters.js"></script>
  </body>
</html>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment