Typing Effect
Description
A small TypeScript package that provides the ability to create a typing effect with one or multiple strings. It is intended for in-browser use.
Ceck the Notes section and demo for more information and examples.
Installation
npm i typing-effect-ts
Or via script tag
Thanks to JSDELIVR
<script type="module">
import { TypingEffect } from "https://cdn.jsdelivr.net/npm/typing-effect-ts/dist/index.js";
const te = new TypingEffect();
</script>
Usage
Say we have a div where we want to otput our strings:
<div id="typing-div">And the output is:<span></span</div>
Provide the instance with string array and a callback function where we set the contents of our div:
import { TypingEffect } from "typing-effect";
const outElem = document.querySelector("#typing-div span");
const te = new TypingEffect(
[
"Children played under the oak tree's branches.",
"Maple leaves whispered in the wind's dance.",
"The pine tree stood tall, a forest guardian.",
],
(string) => {
outElem.innerText = string;
}
);
Then call start on the instance:
te.start();
This results in:
API
TypingEffect instance has several methods which allow you to control the running cycle or alter the behaviour.
start
Starts the iteration over strings. Requires strings and callback to be set. If called while running, restarts iteration from the first string.
Usage:
te.start();
stop
Stops the iteration, preventing any further invocation of the callback function or cycle subscription callbacks.
Usage:
te.stop();
pause
Freezes the current iteration stage and transitions into an idle state. This action triggers the callback function with a blinking cursor if showCursor
option is set to true. This method can only be called after a successful invocation of the start
method.
Usage:
te.pause();
Calling the pause in the middle of typing:
resume
Resumes the iteration after a pause. Affects only the paused instance.
Usage:
te.resume();
jumpTo
Jumps to string under a specified index within the strings array. By default schedules the jump before the next string typing/untyping cycle.
Syntax:
jumpTo: (stringIndex?: number, now?: boolean) => this;
Has two possible arguments:
stringIndex
: Optional number. The index of the string to jump to. Defaults to the current string index.now
: Optional boolean. Indicates whether to execute the jump immediately. Defaults to false.
Usage:
te.jumpTo();
te.jumpTo(2);
te.jumpTo(4, true);
setStrings
Sets the new array of strings for typing/untyping. If called before start
(the instance state is not running), the strings are set immediately. Otherwise, if now
is not provided, executes the setter before the next string's typing/untyping cycle.
After setting starts typing/untyping cycle from the first string of the provided array.
Syntax:
setStrings: (strings: string[], now?: boolean) => this;
Has two possible arguments:
strings
: An array of new strings.now
: Optional boolean. Indicates whether to set new strings immediately. Defaults to false.
Usage:
te.setStrings(["My new favourite string", "My second favourite string"]);
te.setStrings(["My new favourite string", "My second favourite string"], true);
setCallback
Sets the new callback function. If called before start
(the instance state is not running), the callback is set immediately. Otherwise, if now
is not provided, executes the setter before the next string's typing/untyping cycle.
Syntax:
setCallback: (callback: ((string: string) => void) | null, now?: boolean) => this;
Has two possible arguments:
callback
: A function which accepts a string argument.now
: Optional boolean. Indicates whether to set new callback immediately. Defaults to false.
Usage:
te.setCallback((str) => {
});
te.setCallback((str) => {
}, true);
Setting the callback to null
will stop current cycle, set runnig state to idle
and instance state to initialized
. You won't be able to start iteration until a function is set as a callback.
setOptions
Updates the settings of TypingEffect instance. Allows full and partial update. If called before start
(the instance state is not running), the options are set immediately. Otherwise, if now
is not provided, executes the setter before the next string's typing/untyping cycle.
Providing explicit undefined for settings' fields will reset them to their default values.
Syntax:
setOptions: (options?: TypingEffectOptions, now?: boolean) => this;
Has two possible arguments:
options
: Options object. About options.now
: Optional boolean. Indicates whether to update options immediately. Defaults to false.
Usage:
te.setOptions({ typingDelay: 300, cursorBlinkRate: 700 });
te.setOptions({ typingDelay: 300, cursorBlinkRate: 700 }, true);
te.setOptions({ typingDelay: undefined, delayAfterTyping: 1000 });
onBeforeTyping
Registers a callback that will be called before the typing of a string starts. Returns a function that removes the callback.
Syntax:
onBeforeTyping: (callback: (stringIndex: number) => void, once?: boolean) => () => void;
Has two possible arguments:
callback
: A function that will be called with the current string index as its argument.once
: Optional boolean. Indicates whether the callback should be executed only once. Defaults to false.
Usage:
te.onBeforeTyping((index) => {
console.log(index);
}, true);
const removeLogger = te.onBeforeTyping((index) => {
console.log(index);
});
removeLogger();
onAfterTyping
Registers a callback that will be called after the typing of a string finishes. Returns a function that removes the callback.
Syntax:
onAfterTyping: (callback: (stringIndex: number) => void, once?: boolean) => () => void;
Has two possible arguments:
callback
: A function that will be called with the current string index as its argument.once
: Optional boolean. Indicates whether the callback should be executed only once. Defaults to false.
Usage:
te.onAfterTyping((index) => {
console.log(index);
}, true);
const removeLogger = te.onAfterTyping((index) => {
console.log(index);
});
removeLogger();
onBeforeUntyping
Registers a callback that will be called before the untyping of a string starts. Returns a function that removes the callback.
The callback will not be called if untypeString
option is false
.
Syntax:
onBeforeUntyping: (callback: (stringIndex: number) => void, once?: boolean) => () => void;
Has two possible arguments:
callback
: A function that will be called with the current string index as its argument.once
: Optional boolean. Indicates whether the callback should be executed only once. Defaults to false.
Usage:
te.onBeforeUntyping((index) => {
console.log(index);
}, true);
const removeLogger = te.onBeforeUntyping((index) => {
console.log(index);
});
removeLogger();
onAfterUntyping
Registers a callback that will be called after the untyping of a string finishes. Returns a function that removes the callback.
The callback will not be called if untypeString
option is false
.
Syntax:
onAfterUntyping: (callback: (stringIndex: number) => void, once?: boolean) => () => void;
Has two possible arguments:
callback
: A function that will be called with the current string index as its argument.once
: Optional boolean. Indicates whether the callback should be executed only once. Defaults to false.
Usage:
te.onAfterUntyping((index) => {
console.log(index);
}, true);
const removeLogger = te.onAfterUntyping((index) => {
console.log(index);
});
removeLogger();
onArrayFinished
Registers a callback that will be called after all strings in the strings array have been processed. Returns a function that removes the callback.
Syntax:
onArrayFinished: (callback: () => void, once?: boolean) => () => void;
Has two possible arguments:
callback
: A function to be called when array finishes.once
: Optional boolean. Indicates whether the callback should be executed only once. Defaults to false.
Usage:
te.onArrayFinished(() => {
console.log("all strings were processed");
}, true);
const removeLogger = te.onArrayFinished(() => {
console.log("all strings were processed");
});
removeLogger();
dispose
Disposes of the instance, resetting its state and helping to "release" resources. It cancels any ongoing animation frames, resets the running state, and clears all internal data structures. This method should be called when the instance is no longer needed.
While not mandatory, it may be useful in some cases.
After calling dispose
, all subsequent method calls will throw errors.
Usage:
te.dispose()
Options
The options object has the following structure:
type TypingEffectOptions = {
typingDelay?: number | undefined;
untypingDelay?: number | undefined;
delayBeforeTyping?: number | undefined;
delayAfterTyping?: number | undefined;
untypeString?: boolean | undefined;
typingVariation?: number | undefined;
showCursor?: boolean | undefined;
cursorSymbol?: string | Partial<CursorSymbols> | undefined;
cursorBlinkRate?: number | undefined;
loop?: boolean | undefined;
};
type CursorSymbols = {
typing: string;
untyping: string;
blinking: string;
};
typingDelay
number
Delay between typing each character, in milliseconds. Defaults to 100
ms.
untypingDelay
number
Delay between untyping each character, in milliseconds. Defaults to 30
ms.
delayBeforeTyping
number
Delay before starting to type a string, in milliseconds. Defaults to 1600
ms. During this time, if showCursor
setting is true
, the callback function will be called with blinking cursor symbol at the rate of cursorBlinkRate
.
delayAfterTyping
number
Delay after a string is typed, in milliseconds. Defaults to 3000
ms. During this time, if showCursor
setting is true
, the callback function will be called with blinking cursor symbol at the rate of cursorBlinkRate
.
untypeString
boolean
If true, untypes the string after the typing finishes. Defaults to true
. If false
, after delayAfterTyping
is passed, goes straight to delayBeforeTyping
, does not trigger onBeforeUntyping
and onAfterUntyping
.
Setting this option with setOptions
while running restarts cycle from the first string.
typingVariation
number
While typing, a random delay between 0 and the value of typingVariation
is added, creating a subtle impression of natural typing. Setting to 0
, turns the variation off.
Defaults to 100
ms.
showCursor
boolean
If true, a cursor symbol is shown. Defaults to true
.
cursorSymbol
string
| Partial<CursorSymbols>
Allows to set the cursor symbol for typing
, untyping
and blinking
(during delays and while paused). If string is passed as value, uses it for all three stages, otherwise allows to set the symbols individualy via object.
Defaults to "|"
.
Usage:
te.setOptions({ cursorSymbol: "_" });
te.setOptions({
cursorSymbol: {
untyping: "<"
}
});
te.setOptions({
cursorSymbol: {
untyping: undefined
}
});
cursorBlinkRate
number
Blink rate when "idle" - after typing or untyping, or during pause. Defaults to 500
ms.
loop
boolean
Loop to the first string after the last. Defaults to true
.
Notes
Don't expect exact timing in milliseconds. TypingEffect uses requestAnimationFrame, which usually calls its callback around every 16ms (sometimes longer if the website is busy (usually with JS)). This means the shortest reaction time is at least 16ms, so any timing you set will be rounded to the nearest bigger multiple of 16.
For instance, if you set cursorBlinkRate
to 500ms, the cursor will actually blink every 512ms because 500 isn't divisible by 16, but 512 is.