npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

typing-effect-ts

v1.3.5

Published

A small TypeScript package that provides the ability to create a typing effect with one or multiple strings.

Downloads

17

Readme

Typing Effect

| Source | Tests | Coverage | |--------|-------|----------| | main branch | Tests main | Coverage main | | Release | | Coverage release |

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.

Check the Usage notes section and demo for more information and examples. Or take a look at dev notes.

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(); // will restart the iteration of the current string after it finishes
te.jumpTo(2); // will start the iteration from the third string  after the current string finishes
te.jumpTo(4, true); // will start the iteration from the fifth string immediately

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:

// will set new strings and start the iteration from "My new favourite string" after the current string cycle finishes
te.setStrings(["My new favourite string", "My second favourite string"]);

// will set new strings immediately, and start the iteration from "My new 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:

// will set new callback after the current string cycle finishes
te.setCallback((str) => {
  // do stuff
});

// will set new callback immediately
te.setCallback((str) => {
  // do stuff
}, 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:

// will update provided options after the current string cycle finishes
te.setOptions({ typingDelay: 300, cursorBlinkRate: 700 });

// will update options immediately
te.setOptions({ typingDelay: 300, cursorBlinkRate: 700 }, true);

// explicit undefined
te.setOptions({ typingDelay: undefined, delayAfterTyping: 1000 });
// will result in new typingDelay value to reset to default value
// and delayAfterTyping to be set as 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:

// logs the index once before typing
te.onBeforeTyping((index) => {
  console.log(index);
}, true);

// logs the index for every string before typing
const removeLogger = te.onBeforeTyping((index) => {
  console.log(index);
});

// removes the above callback
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:

// logs the index once after typing
te.onAfterTyping((index) => {
  console.log(index);
}, true);

// logs the index for every string after typing
const removeLogger = te.onAfterTyping((index) => {
  console.log(index);
});

// removes the above callback
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:

// logs the index once before untyping
te.onBeforeUntyping((index) => {
  console.log(index);
}, true);

// logs the index for every string before untyping
const removeLogger = te.onBeforeUntyping((index) => {
  console.log(index);
});

// removes the above callback
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:

// logs the index once after untyping
te.onAfterUntyping((index) => {
  console.log(index);
}, true);

// logs the index for every string after untyping
const removeLogger = te.onAfterUntyping((index) => {
  console.log(index);
});

// removes the above callback
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:

// logs the message once
te.onArrayFinished(() => {
  console.log("all strings were processed");
}, true);

// logs the message every time array is finished
const removeLogger = te.onArrayFinished(() => {
  console.log("all strings were processed");
});

// removes the above callback
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 100ms.

untypingDelay

number

Delay between untyping each character, in milliseconds. Defaults to 30ms.

delayBeforeTyping

number

Delay before starting to type a string, in milliseconds. Defaults to 1600ms. 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 3000ms. 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 100ms.

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:

// will set the cursor to "_" wile typing, untyping and blinking
te.setOptions({ cursorSymbol: "_" });

// will set only the untyping cursor to "<", leaving the default "|" for typing and blinking
te.setOptions({
  cursorSymbol: {
    untyping: "<"
  }
});

// cursor values can be reset to default if set to `undefined`
// will reset untyping cursor to "|"
te.setOptions({
  cursorSymbol: {
    untyping: undefined
  }
}); 

cursorBlinkRate

number

Blink rate when "idle" - after typing or untyping, or during pause. Defaults to 500ms.

loop

boolean

Loop to the first string after the last. Defaults to true.

Usage notes

Timing

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.

Layout shift

Important! If you are using TypingEffect as in the examples to set the content of some element, it's essential to remember the layout shift. See the demo for context. It is bad UX practice since it causes content jitter, making it harder for people to process; therefore, it should be avoided. The simplest way is to check the maximum height of the container during the cycle and set it's height or min-height accordingly.

If this does not meet your requirements, refer to the solution in the demo for layout shift to understand how it can be dynamically resolved.