SplitType Documentation

repository·master·Indexed 20 days ago

https://github.com/lukepeavey/splittype

A lightweight JavaScript library (v0.3.4) that splits HTML text into individual lines, words, and characters. It enables granular animations by wrapping text units in manageable elements, providing support for Unicode symbols, nested HTML preservation, and custom class names. It includes methods to revert text to its original state and a .split() method for handling responsive reflows via ResizeObserver.

Tokens
4.2K
Snippets
23
Records
28
Agent score
71%

What's inside SplitType

  1. What is SplitType

    master

    SplitType is a lightweight JavaScript library designed to split HTML text into individual elements (lines, words, or characters). This allows you to animate these components independently using any animation library (such as GSAP).

    Under the hood, SplitType modifies the HTML structure of your target elements by wrapping each split unit in its own element.

  2. How nested elements are handled

    master

    As of v0.3, SplitType preserves nested elements (like <em>, <a>, or <button>) within the text. This allows you to maintain interactivity and custom styling within split text.

    Caveat: This feature is not fully compatible with lines splitting. If a nested element's content spans multiple lines, it may cause unexpected line breaks. Use nested elements with lines only if you can ensure they do not wrap.

    <p id="target">Foo <em id="nested">Bar</em></p>
    // The <em> element will be preserved in the DOM tree
    SplitType.create('#target')
  3. Key features of SplitType

    master

    SplitType provides several capabilities for text manipulation:

    • Granular Splitting: Split text into lines, words, and/or characters.
    • Customization: Define custom class names for the generated split elements.
    • Line Break Detection: Automatically detects natural line breaks in text.
    • Tag Preservation: Preserves explicit <br> tags and nested HTML elements within the target elements.
    • Unicode Support: Supports unicode symbols, including emojis.
  4. How to split text with SplitType

    master

    SplitType splits HTML text into elements (lines, words, or characters) to allow for independent animation. You can instantiate it using the new keyword or the static SplitType.create() method.

    Important CSS Requirement To prevent characters from shifting slightly when text is split or reverted, apply the following style to all target elements:

    .target {
      font-kerning: none;
    }

    If the target elements are inside a flex container, they must have a defined width to prevent movement during the split process.

    Basic Usage

    // Using the constructor
    const text = new SplitType('#target')
    
    // Using the static create method
    const text = SplitType.create('#target')
    const text = new SplitType('#target')
  5. Handle responsive text with `split()`

    master

    When using absolute: true or splitting by lines, the text will not automatically reflow when the container resizes. To maintain correct layout, you must call the .split() method on your SplitType instance when a resize occurs (e.g., via a ResizeObserver).

    When using relative positioning with words and chars, reflow is handled automatically by the browser.

    const instance = new SplitType('#target', { types: 'words, chars', absolute: true })
    let previousContainerWidth = null
    
    function handleResize(entry) {
      const [{ contentRect }] = entry
      const width = Math.floor(contentRect.width)
    
      // Re-split if the width has changed
      if (previousContainerWidth && previousContainerWidth !== width) {
        instance.split()
      }
      previousContainerWidth = width
    }
    
    const resizeObserver = new ResizeObserver(handleResize)
    resizeObserver.observe(document.querySelector('.container'))
  6. Install SplitType via npm or CDN

    master

    You can install SplitType as a dependency using npm or yarn, or include it directly in your HTML via a CDN.

    NPM/Yarn

    yarn add 'split-type'

    Importing in JavaScript

    import SplitType from 'split-type'

    CDN Include the following script tag in your HTML:

    <script src="https://unpkg.com/split-type"></script>
    yarn add 'split-type'
  7. Handle responsive text with ResizeObserver

    master

    When using relative positioning (the default) with words and chars, text reflows naturally. However, if you use absolute: true or split by lines, the text will not reflow automatically when the container resizes.

    To handle this, you must call instance.split() when the container changes size. It is best practice to use a ResizeObserver and a debounce function to avoid excessive calls.

    const text = new SplitType('#target')
    
    const resizeObserver = new ResizeObserver(
      debounce(([entry]) => {
        // Re-split the text to recalculate positions
        text.split()
      }, 500)
    )
    resizeObserver.observe(containerElement)
    const text = new SplitType('#target')
    
    const resizeObserver = new ResizeObserver(
      debounce(([entry]) => {
        text.split()
      }, 500)
    )
    resizeObserver.observe(containerElement)
  8. Configure the types of text splitting

    master

    The types option (or its alias split) allows you to specify which units the text should be broken into. The available types are lines, words, and chars.

    Note: It is not recommended to split text into only characters; to maintain natural line breaks, you should include words or lines in your selection.

    // Default: splits into lines, words, and characters
    const text = new SplitType('#target')
    
    // Splits text into words and characters
    const text = new SplitType('#target', { types: 'words, chars' })
    
    // Splits text into lines only
    const text = new SplitType('#target', { types: 'words' })
    const text = new SplitType('#target', { types: 'words, chars' })
  9. Configure text splitting with the `types` option

    master

    The types option determines which units the text is broken into. Supported types are lines, words, and chars. You can provide a comma-separated string to specify combinations.

    Note: For multi-line text, you should include words and/or lines in the types list. Splitting into chars only may cause unexpected line breaks.

    // Splits text into lines, words, and characters (default behavior)
    const text = new SplitType('#target')
    
    // Splits text into words and characters
    const text = new SplitType('#target', { types: 'words, chars' })
    
    // Splits text into lines
    const text = new SplitType('#target', { types: 'words' })
  10. Animate split characters with GSAP

    master

    Since the SplitType instance provides arrays of elements (lines, words, chars), you can easily pass them to animation libraries like GSAP for staggered effects.

    // Split text into words and characters
    const text = new SplitType('#target', { types: 'words, chars' })
    
    // Animate characters into view with a stagger effect
    gsap.from(text.chars, {
      opacity: 0,
      y: 20,
      duration: 0.5,
      stagger: { amount: 0.1 },
    })