A customizable typing animation component with support for multiple words, cursor styles, and animation controls.
<script lang="ts"> import { TypingAnimation } from "$lib/components/magic/typing-animation/index.js";</script>
<TypingAnimation content="hello, svelte." class="text-2xl leading-relaxed font-normal tracking-normal"/>Installation
Install dependencies
Install the required packages for this component:
Copy the Source Code
Copy and paste the following code into your project:
<script lang="ts"> import type { ClassValue } from "svelte/elements"; import { motion, type MotionProps, inView } from "motion-sv"; import { cn } from "#lib/utils.js"; import { watch } from "runed";
interface TypingAnimationProps extends MotionProps { content?: string; // Single text string to type words?: string[]; // Array of words to cycle through class?: ClassValue; duration?: number; typeSpeed?: number; deleteSpeed?: number; delay?: number; pauseDelay?: number; loop?: boolean; startOnView?: boolean; showCursor?: boolean; blinkCursor?: boolean; cursorStyle?: "line" | "block" | "underscore"; }
let { content, words, class: className, duration = 100, typeSpeed, deleteSpeed, delay = 0, pauseDelay = 1000, loop = false, startOnView = true, showCursor = true, blinkCursor = true, cursorStyle = "line", ...props }: TypingAnimationProps = $props();
let displayedText = $state(""); let currentWordIndex = $state(0); let currentCharIndex = $state(0); let phase = $state<"typing" | "pause" | "deleting">("typing");
let elementRef: HTMLElement | null = $state(null);
let wordsToAnimate = $derived(words || (content ? [content] : [])); let hasMultipleWords = $derived(wordsToAnimate.length > 1); let typingSpeed = $derived(typeSpeed || duration); let deletingSpeed = $derived(deleteSpeed || typingSpeed / 2);
// State: Track if element is in view let isInView = $state(false);
// Watch elementRef to setup inView detection watch( () => elementRef, () => { if (!startOnView) { isInView = true; return; }
if (!elementRef) return;
// Use motion-sv's inView for detection const cleanup = inView( elementRef, () => { isInView = true; }, { amount: 0.3 } );
return cleanup; } );
// Derived: Should animation start let shouldStart = $derived(startOnView ? isInView : true);
// Animation loop using watch - only watches shouldStart let timeoutId: ReturnType<typeof setTimeout> | undefined;
let runAnimation = () => { if (!shouldStart || wordsToAnimate.length === 0) return;
const currentWord = wordsToAnimate[currentWordIndex] || ""; const graphemes = Array.from(currentWord);
// Calculate delay based on current phase and initial delay const timeoutDelay = delay > 0 && displayedText === "" ? delay : phase === "typing" ? typingSpeed : phase === "deleting" ? deletingSpeed : pauseDelay;
timeoutId = setTimeout(() => { switch (phase) { case "typing": // Type next character if (currentCharIndex < graphemes.length) { displayedText = graphemes.slice(0, currentCharIndex + 1).join(""); currentCharIndex = currentCharIndex + 1; runAnimation(); // Continue animation } else { // Finished typing current word if (hasMultipleWords || loop) { const isLastWord = currentWordIndex === wordsToAnimate.length - 1; if (!isLastWord || loop) { phase = "pause"; runAnimation(); // Continue animation } } } break;
case "pause": // Move to deleting phase after pause phase = "deleting"; runAnimation(); // Continue animation break;
case "deleting": // Delete previous character if (currentCharIndex > 0) { displayedText = graphemes.slice(0, currentCharIndex - 1).join(""); currentCharIndex = currentCharIndex - 1; runAnimation(); // Continue animation } else { // Finished deleting, move to next word const nextIndex = (currentWordIndex + 1) % wordsToAnimate.length; currentWordIndex = nextIndex; phase = "typing"; runAnimation(); // Continue animation } break; } }, timeoutDelay); };
// Watch only shouldStart - animation state changes won't retrigger watch( () => shouldStart, () => { // Clear any existing timeout if (timeoutId) clearTimeout(timeoutId);
// Reset state displayedText = ""; currentWordIndex = 0; currentCharIndex = 0; phase = "typing";
// Start animation if shouldStart is true if (shouldStart && wordsToAnimate.length > 0) { runAnimation(); } } );
// Derived: Current word as array of graphemes let currentWordGraphemes = $derived(Array.from(wordsToAnimate[currentWordIndex] || ""));
// Derived: Animation is complete (not looping and finished last word) let isComplete = $derived( !loop && currentWordIndex === wordsToAnimate.length - 1 && currentCharIndex >= currentWordGraphemes.length && phase !== "deleting" );
// Derived: Should show cursor let shouldShowCursor = $derived( showCursor && !isComplete && (hasMultipleWords || loop || currentCharIndex < currentWordGraphemes.length) );
// Helper: Get cursor character based on style function getCursorChar() { switch (cursorStyle) { case "block": return "▌"; case "underscore": return "_"; case "line": default: return "|"; } }</script>
<!-- Render motion component as span --><motion.span bind:ref={elementRef} class={cn("leading-20 tracking-[-0.02em]", className)} {...props}> {displayedText} {#if shouldShowCursor} <span class={cn("inline-block", blinkCursor && "animate-blink-cursor")}> {getCursorChar()} </span> {/if}</motion.span> import TypingAnimation from "./typing-animation.svelte";export { TypingAnimation };Folder Structure
src/└── lib/ └── components/ └── magic/ └── typing-animation/ ├── typing-animation.svelte └── index.tsInstall and integrate the Svelte component documented below.https://sv-animations.vercel.app/magic/docs/components/typing-animation/llms.txt
Follow the guide's installation and usage instructions.Match the project's existing structure, imports, and styles.Keep changes scoped to the component and verify it works.Reply with a short bullet list of completed changes.Usage
<script lang="ts"> import { TypingAnimation } from "#lib/components/magic/typing-animation/index.js";</script>
<TypingAnimation content="hello, svelte." class="text-2xl leading-relaxed font-normal tracking-normal" />Examples
Cursor Blinking
Compare a blinking cursor with a steady cursor.
blinking
|steady
|<script lang="ts"> import { TypingAnimation } from "$lib/components/magic/typing-animation/index.js";</script>
<div class="grid gap-6"> {#each [true, false] as blinkCursor} <div> <p class="text-muted-foreground mb-2 text-xs">{blinkCursor ? "blinking" : "steady"}</p> <TypingAnimation content="take your time" {blinkCursor} pauseDelay={2000} loop class="text-xl leading-relaxed font-normal tracking-normal" /> </div> {/each}</div>Cursor Styles
Compare line, block, and underscore cursors at the same text size.
line
|block
▌underscore
_<script lang="ts"> import { TypingAnimation } from "$lib/components/magic/typing-animation/index.js";
const cursors = ["line", "block", "underscore"] as const;</script>
<div class="grid gap-6"> {#each cursors as cursorStyle} <div> <p class="text-muted-foreground mb-2 text-xs">{cursorStyle}</p> <TypingAnimation content="choose a cursor" {cursorStyle} loop class="font-mono text-lg leading-relaxed font-normal tracking-normal" /> </div> {/each}</div>Single Play
Cycle through three words once and keep the last word visible.
<script lang="ts"> import { TypingAnimation } from "$lib/components/magic/typing-animation/index.js";</script>
<TypingAnimation words={["install", "configure", "ready"]} loop={false} class="text-xl leading-relaxed font-normal tracking-normal"/>Custom Speed
Type quickly and delete slowly with separate speed controls.
<script lang="ts"> import { TypingAnimation } from "$lib/components/magic/typing-animation/index.js";</script>
<TypingAnimation words={["quick typing", "slow deletion"]} typeSpeed={50} deleteSpeed={150} pauseDelay={1500} loop class="text-xl leading-relaxed font-normal tracking-normal"/>Multiple Words
Rotate through a short list of words without extra decoration.
<script lang="ts"> import { TypingAnimation } from "$lib/components/magic/typing-animation/index.js";</script>
<TypingAnimation words={["components", "transitions", "interactions"]} loop class="text-xl leading-relaxed font-normal tracking-normal"/>Start On View
Type a single line when it enters the viewport.
<script lang="ts"> import { TypingAnimation } from "$lib/components/magic/typing-animation/index.js";</script>
<TypingAnimation content="typing starts in view" startOnView class="text-xl leading-relaxed font-normal tracking-normal"/>Command Line
Type an installation command once with a block cursor.
<script lang="ts"> import { TypingAnimation } from "$lib/components/magic/typing-animation/index.js";</script>
<div class="bg-muted/30 flex w-full max-w-md items-center gap-3 overflow-x-auto rounded-lg border px-4 py-5 font-mono"> <span class="text-muted-foreground text-sm" aria-hidden="true">$</span> <TypingAnimation content="pnpm add motion-sv runed" cursorStyle="block" typeSpeed={65} class="text-sm leading-relaxed font-normal tracking-normal whitespace-nowrap" /></div>Inline Rotation
Keep a sentence still while the final words rotate.
explore |
<script lang="ts"> import { TypingAnimation } from "$lib/components/magic/typing-animation/index.js";</script>
<p class="text-xl leading-relaxed font-normal"> explore <TypingAnimation words={["components", "examples", "source code"]} loop class="inline-block min-w-[12ch] text-xl leading-relaxed font-normal tracking-normal" /></p>Props
Typing Animation
A versatile typing animation component with support for single text, multiple words, cursor customization, and animation controls.
| Name | Type | Default | Description |
|---|---|---|---|
content | string | undefined | Single text string to type (use this OR words) |
words | string[] | undefined | Array of words to cycle through (use this OR content) |
class | ClassValue | "" | Additional CSS classes to apply |
duration | number | 100 | Default duration for typing speed (ms per character) |
typeSpeed | number | duration | Speed for typing characters (ms per character) |
deleteSpeed | number | typeSpeed / 2 | Speed for deleting characters (ms per character) |
delay | number | 0 | Initial delay before animation starts (ms) |
pauseDelay | number | 1000 | Delay between typing and deleting (ms) |
loop | boolean | false | Whether to loop the animation continuously |
startOnView | boolean | true | Start animation when element enters viewport |
showCursor | boolean | true | Show the typing cursor |
blinkCursor | boolean | true | Make the cursor blink during pause |
cursorStyle | 'line' | 'block' | 'underscore' | 'line' | Style of the cursor ('line': |, 'block': ▌, 'underscore': _) |