Web Development

Animating Text with GSAP: SplitText Lines, ScrambleText and TextPlugin

Team Nippysoft
• • 8 min read
Animating Text with GSAP: SplitText Lines, ScrambleText and TextPlugin

GSAP ships three plugins for animating text. SplitText breaks an element into characters, words or lines so each piece can move; ScrambleText decodes it through random characters, and TextPlugin types it one character at a time. All three have been free since 3.13.

An app's launch page uses them together: the intro paragraph rises line by line, the version name decodes itself like a terminal, and the tagline types itself out. That is the second demo in this post.

This post is part of the GSAP series. Licensing and installation live in the series hub, and stagger, matchMedia and context in post 2, on the core. It includes two live demos on GSAP 3.15.0. Four script tags are enough:

<script src="https://unpkg.com/gsap@3.15.0/dist/gsap.min.js"></script>
<script src="https://unpkg.com/gsap@3.15.0/dist/SplitText.min.js"></script>
<script src="https://unpkg.com/gsap@3.15.0/dist/ScrambleTextPlugin.min.js"></script>
<script src="https://unpkg.com/gsap@3.15.0/dist/TextPlugin.min.js"></script>
<script>
  gsap.registerPlugin(SplitText, ScrambleTextPlugin, TextPlugin);
</script>

If one of the files is missing, the registerPlugin line throws a ReferenceError. Without ScrambleText or TextPlugin, its property is ignored with a warning ("Missing plugin?"); without SplitText, SplitText.create() throws another ReferenceError. In the snippets, .intro, .headline and .sentence are elements on the page.

SplitText: a heading that builds letter by letter

SplitText "splits an HTML element's text into individual characters, words, and/or lines". The entry point is SplitText.create(); here it splits the page's h1:

SplitText.create("h1", {
  type: "words, chars",
  mask: "chars",
  autoSplit: true,
  onSplit(self) {
    return gsap.from(self.chars, {
      yPercent: 100,
      duration: 0.6,
      ease: "power2.out",
      stagger: 0.03
    });
  }
});

What each option does:

  • type picks the units. With "words, chars", letters stay grouped inside their words.
  • mask wraps each piece in an extra clipping element, so a letter sliding up only appears as it crosses the edge.
  • autoSplit: true re-splits the text after fonts finish loading or when the width changes, but only when lines are split: with "words, chars", as here, it does nothing.
  • onSplit() is where the animation belongs when autoSplit is on. If it returns the animation, SplitText cleans it up and keeps it in sync on every re-split.

On a heading, accessibility is handled: aria is "auto", and the SplitText docs state that it "Adds aria-label to the split element(s) and aria-hidden to the freshly-created line/word/character elements". Screen readers announce the heading as one phrase. A paragraph needs one more step, in the accessibility section.

The instance's revert() brings the original markup back: "Restore the element's original innerHTML anytime with revert()".

Every letter in its own time

Masked lines

With type: "lines" and mask: "lines", every line sits in a wrapper that clips it, and yPercent: 100 makes it rise from below its row. The masks land in self.masks, and only one type can be masked: if mask asks for two, or for a type missing from type, there are no masks and no warning. The official example, without a mask:

SplitText.create(".intro", {
  type: "lines",
  autoSplit: true,
  onSplit: (self) => {
    return gsap.from(self.lines, { y: 100, opacity: 0, stagger: 0.05 });
  }
});

With a mask, as in the second demo:

SplitText.create(".intro", {
  type: "lines",
  mask: "lines",
  autoSplit: true,
  onSplit(self) {
    return gsap.from(self.lines, {
      yPercent: 100,
      duration: 0.7,
      ease: "power3.out",
      stagger: 0.12
    });
  }
});

The docs describe the mask as "visibility: clip", but their own example and the style the browser ends up with both use overflow: clip, which is what does the clipping.

Why lines are fragile

Characters and words reflow on their own when the width changes. Lines do not, because each one encloses a fixed set of words. If the container narrows or the font loads late, "the last word in a line may shift down to the next", and the only fix is to split again.

That is what autoSplit: true does. If onSplit() returns the animation, SplitText carries its totalTime() over to the new one, so the swap is barely visible. Without autoSplit, the split has to wait for document.fonts.ready:

document.fonts.ready.then(() => {
  const split = SplitText.create(".intro", { type: "lines", mask: "lines" });
  gsap.from(split.lines, { yPercent: 100, stagger: 0.12 });
});

When the split runs while the font loads, the lines come from the fallback font; once the real one arrives, one no longer fits its row. SplitText prints no warning.

Three more tips from the docs: splitting only what is needed, since thousands of elements get expensive; font-kerning: none and text-rendering: optimizeSpeed when letters shift after splitting; and no SVG <text> nodes.

Accessibility: headings yes, paragraphs get a copy

aria: "auto" puts an aria-label with the full text on the split element, and that label is what a screen reader reads instead of the pieces, which get aria-hidden. On a heading that is allowed. On a paragraph (<p>), a <div> or a <span> it is not: WAI-ARIA 1.2 says "Authors MUST NOT use the aria-label or aria-labelledby attributes to name the element". On a paragraph, the text sits in a prohibited attribute.

The rule in this post: aria: "auto" only on headings. On a <p> or a <div>, aria: "hidden" plus a plain copy of the text next to it. aria: "hidden" also puts aria-hidden on the paragraph itself, so without the copy a screen reader gets nothing at all. The sr-only class hides that copy on screen, but screen readers still read it. That is what the docs recommend for nested elements:

<p class="sr-only">Each line rises from its mask.</p>
<p class="intro" aria-hidden="true">Each line rises from its mask.</p>

<style>
  .sr-only {
    position: absolute;
    width: 1px;
    height: 1px;
    margin: -1px;
    padding: 0;
    overflow: hidden;
    clip: rect(0, 0, 0, 0);
    white-space: nowrap;
    border: 0;
  }
</style>

<script>
  SplitText.create(".intro", { type: "lines", mask: "lines", aria: "hidden" });
</script>

The same pattern fits ScrambleText and TextPlugin, which rewrite the text on every frame; without the copy, a screen reader could land on random letters. The official ScrambleText demo does the same, with its animated text under aria-hidden="true".

ScrambleText: text that decodes itself

ScrambleText swaps the text for random characters that keep refreshing while it reveals the final text, left to right. "Visually it looks like a computer decoding a string of text", and the docs pitch it as "Great for rollovers". With an object:

gsap.to(".headline", {
  duration: 1.6,
  scrambleText: {
    text: "{original}",
    chars: "upperCase",
    revealDelay: 0.4,
    speed: 0.4
  }
});

text is the final text, and "{original}" decodes back into what was there. The docs say the same happens when it is left out, but on GSAP 3.15.0 an object without text leaves the element empty. chars picks the jumble: "upperCase" by default, "lowerCase", "upperAndLowerCase" or a custom string (a typo such as "upperCas" scrambles with those letters, with no error). revealDelay holds the reveal back, and speed (1 by default) sets how often the characters refresh. There is also tweenLength (on by default: the length changes gradually), delimiter: " " to reveal word by word, rightToLeft and newClass/oldClass. The result is plain text: an <em> inside the headline is lost.

TextPlugin: text that types itself

TextPlugin "Replaces the text content of a DOM element one character at a time", or word by word with delimiter: " ". Rewind or restart a to() tween and the old text comes back. Typing from empty takes fromTo() with text: "" and ease: "none", so every letter takes the same time (eases are in post 4):

gsap.fromTo(".sentence", { text: "" }, {
  duration: 1.6,
  text: { value: "This sentence types itself letter by letter" },
  ease: "none"
});

Options go inside text: { value, … }. speed scales the duration to the changes ("0.05 / speed * text_changes"), type: "diff" animates only what differs, and padSpace pads with non-breaking spaces when the new text is shorter. There are also preserveSpaces, rtl and newClass/oldClass, and it honors <br> tags.

The demo: three headlines

The second demo puts all three together, all under aria-hidden with their copy. Under reduced motion it does not start by itself: the texts sit in their final state and the buttons play them, through gsap.matchMedia(), as covered in post 2. To reveal text on scroll, the groundwork is in post 5.

1. SplitText by lines

Each line rises from under its own mask, one after another, without leaving its row.

2. ScrambleText

Decoding the headline

3. TextPlugin

This sentence types itself letter by letter

Common mistakes

  1. Animating outside onSplit() with autoSplit. Every re-split creates new elements. An animation created outside onSplit() keeps pointing at the old ones, which are no longer on the page, and the new lines never move.
  2. Splitting by chars alone. The result is "odd breaks at the very end of lines": in a narrow box, a long word ends up split across two rows. The fix is adding words or lines to type, or smartWrap: true.
  3. Splitting before fonts load, without autoSplit. The fix is autoSplit or document.fonts.ready.
  4. text-wrap: balance on split text. The docs warn that "it interferes with clean text splitting".
  5. TextPlugin options outside text. The docs flag as "BAD" putting newClass or delimiter in the main vars; they belong in text: { value, … }. Outside it, GSAP logs a warning ("Invalid property delimiter") and types letter by letter.
  6. aria: "auto" on a <p> or a <div>. It leaves an aria-label that ARIA prohibits there. The fix is aria: "hidden" and a copy.

FAQ

Does SplitText hurt the SEO of the h1?

Per the docs, when the main h1 is split, the page needs proper title and description meta tags, and SplitText should stay on aria: "auto", the default. Otherwise the heading may show up in Google results broken into its parts.

ScrambleText or TextPlugin?

ScrambleText decodes out of a jumble of characters; TextPlugin types one character at a time, with no noise. Both rewrite the element's text while they run, so both call for the screen reader copy.

Conclusion

The basics live in the series hub, post 2, post 3 (timelines), post 4 and post 5. Next up is post 7, on Flip, and in post 13, the final tutorial, the landing page headline comes in with SplitText.

References

Subscribe

Get the latest posts delivered right to your inbox.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Comments

No comments yet. Be the first to share your thoughts!

Subscribed!

Registered! A confirmation link has been sent to your email address. If you don't see it, please check your spam folder.

Error

An error occurred. Please try again.

Full code