Create Smooth Looping Typewriter Effects with Typewriter.js

Category: Animation , Javascript , Text | January 16, 2025
AuthorDoctorDemon
Last UpdateJanuary 16, 2025
LicenseMIT
Views92 views
Create Smooth Looping Typewriter Effects with Typewriter.js

Typewriter.js is a lightweight JavaScript library that creates smooth typewriter typing and deleting effects on any text content.

It introduces a <Typewriter /> component that animates text content sequentially within the component to mimic a text rotator effect. Each text segment types out character by character, pauses, then deletes before moving to the next segment.

For instance, you could use it to display “CSSScript.Com” then “A JavaScript & CSS website.” and finally “Update Daily.” This visual cue can engage users more effectively than static text.

See It In Action:

How to use it:

1. Download and load the ‘Typewriter.js’ script in the document.

<script src="typewriter.js"></script>

2. Use the <typewriter> custom element within your HTML where you want the typewriter effect. Place the text you want animated inside this element. Each direct child element within <typewriter> will be animated one after the other. You can then customize the animation with optional attributes: pause, typing-speed, untyping-speed, and loop.

<typewriter pause="2" typing-speed="100" untyping-speed="100" loop="true">
  <span>CSSScript.Com</span>
  <span>A JavaScript & CSS website</span>
  <span>Update Daily.</span>
</typewriter>

How it works:

When the page loads, the library selects all <Typewriter /> elements present on the page. For each element found, it retrieves its child elements, which contain the text to be animated. It also fetches the values of the optional attributes: pause, typing-speed, untyping-speed, and loop.

The library then clears the initial content of the <Typewriter /> element. It uses variables i and j to keep track of the current character being typed and the current child element, respectively. The typing variable determines whether the animation is currently in the typing or untyping phase.

The core of the animation lies within the type function. If typing is true, it progressively reveals characters of the current element’s text content. The innerHTML of the <Typewriter /> is updated to show the typed characters. setTimeout is used to introduce delays based on the typingSpeed. Once the entire text of the current element is typed, it checks if looping is enabled or if there are more elements to process. If so, it transitions to the untyping phase after a pause.

If typing is false, the function progressively removes characters from the displayed text, simulating the untyping effect, with delays controlled by untypingSpeed. Once the text is fully untyped, it moves to the next child element (or loops back to the first if looping is enabled) and starts the typing process again. This sequence continues, creating the typewriter effect.

You Might Be Interested In:


Leave a Reply