@kojodesign/split-text
A lightweight library for splitting text into individual characters, words, and lines for animations and styling.
Features
- Split text into characters, words, and lines
- Preserve HTML structure with recursive splitting
- Customizable CSS classes
- TypeScript support
- Zero dependencies
Installation
pnpm install
Usage
Basic Text Splitting
import { splitText } from "@kojodesign/split-text";
const result = splitText("#my-element");
result.chars.forEach((char) => {
});
result.words.forEach((word) => {
});
result.lines.forEach((line) => {
});
Recursive Text Splitting
Perfect for preserving HTML structure while splitting text in nested elements:
<div id="container">
<h1>Main Title</h1>
<p>First paragraph with some text</p>
<p>Second paragraph with more text</p>
<span>Some span text</span>
</div>
const result = splitText("#container", { recursive: true });
Options
splitText("#element", {
splitBy: " ",
classNames: {
word: "word",
char: "char",
line: "line",
},
recursive: false,
filter: (element) => boolean,
inline: false,
});
Filter Option
When using recursive: true
, you can use the filter
option to selectively process elements:
splitText("#container", {
recursive: true,
filter: (element) => element.tagName.toLowerCase() === "p"
});
splitText("#container", {
recursive: true,
filter: (element) => !element.classList.contains("no-split")
});
splitText("#container", {
recursive: true,
filter: (element) => element.hasAttribute("data-split")
});
Display Style
By default, all split elements use display: inline-block
. You can change this to display: inline
with the inline
option:
splitText("#element", {
inline: true
});
Examples
Animation with GSAP
import { splitText } from "@kojodesign/split-text";
import { gsap } from "gsap";
const { chars } = splitText("#animated-text", {
classNames: {
char: "animated-char"
}
});
gsap.from(chars, {
opacity: 0,
y: 20,
duration: 0.5,
stagger: 0.02,
});
Recursive Animation
const { words } = splitText("#article", {
recursive: true,
classNames: {
word: "animated-word"
}
});
gsap.from(words, {
opacity: 0,
y: 10,
duration: 0.3,
stagger: 0.01,
});
Development
To run tests:
pnpm test
``