text-slicer
v1.5.0
Published
TextSlicer is designed to split text within an HTML element into separate words and/or characters, wrapping each word and/or character in separate span elements.
Maintainers
Readme
➠ Install
yarn add text-slicer➠ Import
import { TextSlicer } from 'text-slicer';➠ Usage
const textSlicer = new TextSlicer();
textSlicer.init();Initialization with specified parameters
document.addEventListener('DOMContentLoaded', () => {
const textSlicer = new TextSlicer({
container: '.text-slicer',
splitMode: 'both',
cssVariables: true,
dataAttributes: true,
}, {
onAfterRender: (metrics) => console.log(metrics)
});
textSlicer.init();
});How to apply the TextSlicer class to all elements on a page
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.text-slicer').forEach((element) => {
const textSlicer = new TextSlicer({ container: element });
textSlicer.init();
});
});➠ Options
| Option | Type | Default | Description |
|:--------------------:|:-----------------------:|:------------:|:---------------------------------------------------------------------------------------------------------------------------------------------------------|
| container | HTMLElement \| string | undefined | The target element or selector for text splitting. |
| splitMode | 'words' \| 'chars' \| 'both' | both | Defines splitting mode: by words, characters, or both. |
| cssVariables | boolean | false | Enables CSS variables like --word-index and --char-index for each span. |
| dataAttributes | boolean | false | Adds data-word and data-char attributes for additional styling or scripting. |
| keepWhitespaceNodes| boolean | true | If false, whitespace nodes will be ignored when splitting characters. |
| containerHeightVar | boolean | false | If true, sets a dynamic CSS variable --container-height that updates on resize. |
➠ Callbacks
| Callback | Arguments | Description |
|-----------------|-----------------------|---------------------------------------------------------------------------------------------------------|
| onAfterRender | TextSlicerMetrics | Invoked after rendering. Provides wordTotal, charTotal, and renderedAt timestamp. |
➠ API Methods
| Method | Description |
|-------------------|--------------------------------------------------------------------------------------------------|
| init() | Initializes and renders text splitting. |
| reinit(newText?, options?) | Re-initializes with optional new text and updated options. |
| clear() | Clears all content inside the container element. |
| split() | Manually triggers splitting and rendering. |
| destroy() | Cleans up instance, observers, and styles. |
| updateOptions() | Updates options at runtime and re-renders if mounted. |
| lockHeight() | Locks container height to its measured value. |
| unlockHeight() | Unlocks container height. |
| metrics (getter)| Returns current metrics: wordTotal, charTotal, and renderedAt. |
➠ License
text-slicer is released under MIT license
