Discover how to generate captivating text animations with typewriter effects using Anime.js!

Hey there! I'm currently experimenting with different animations using anime js. My latest goal is to achieve a Typewriter Effect for text using anime.js, similar to this awesome live demo here.

Here's what I've got so far.

HTML:

<div class="text-animation">
  Welcome to codingflag
</div>

CSS:

body {
  margin:0px;
  height:100vh;
  display:flex;
  align-items:center;
  justify-content:center;
  background:#222;
}
.text-animation {
  color:#f5f5f5;
  font-size:50px;
  font-family:"Passion One",sans-serif;
  letter-spacing:1px;
}
.text-animation .letter {
  display:inline-block;
}

JavaScript:

var element = document.getElementsByClassName("text-animation")[0];
element.innerHTML = element.textContent.replace(/\S/g,'<span class="letter">$&</span>');
anime.timeline({loop:true})
.add({
  targets:'.text-animation .letter',
  scale:[3,1],
  opacity:[0,1],
  translateZ:0,
  duration:1000,
  easing:"easeOutExpo",
  delay:(elem, index) => index*70
})
.add({
  targets:'.text-animation',
  opacity:0,
  duration:1000,
  delay:1000,
  easing:"easeOutExpo"
})

Check out my CODEPEN example: type writer effect.

What else should I include to achieve the desired result like the one in the provided sample?

Answer №1

The most challenging aspect of this text animation is the calculation of the offset for the cursor, which can be easily achieved by utilizing a combination of HTMLElement.offsetLeft and HTMLElement.offsetWidth for each letter within the word.

const element = document.querySelector('.text-animation');
  const lettersHtml = element.textContent.replace(/\S/g, '<span class="letter">$&</span>');
  element.innerHTML = `<div class="letters">${lettersHtml}</div><span class="cursor"></span>`;
  element.style.display = 'block';

  const letters = Array.from(element.querySelectorAll('.letter'));
  const TYPE_AFTER_MS = 3_000;
  const JUMP_AFTER_MS = 250;

  const blink = anime({
    targets: '.text-animation .cursor',
    loop: true,
    duration: 750,
    opacity: [
      {value: [1, 1]},
      {value: [0, 0]}
    ],
  });

  anime.timeline({loop: true})
    .add({
      targets: '.text-animation .cursor',
      translateX: letters.map((letter, i) =>
        ({value: letter.offsetLeft + letter.offsetWidth, duration: 1, delay: i === 0 ? 0 : JUMP_AFTER_MS}))
    }, TYPE_AFTER_MS)
    .add({
      targets: '.text-animation .letter',
      opacity: [0, 1],
      duration: 1,
      delay: anime.stagger(JUMP_AFTER_MS),
      changeBegin: () => {
        blink.reset();
        blink.pause();
      },
      changeComplete: () => {
        blink.restart();
      }
    }, TYPE_AFTER_MS)
    .add({
      targets: '.text-animation',
      opacity: 0,
      duration: 1000,
      delay: 500,
      easing: 'easeOutExpo',
    });
body {
  margin: 0;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #222;
}

.text-animation {
  display: none;
  position: relative;
  color: #f5f5f5;
  font-size: 50px;
  font-family: "Passion One", sans-serif;
  letter-spacing: 1px;
  line-height: 1;
}

.text-animation .letter {
  display: inline-block;
  opacity: 0;
}

.cursor {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 3px;
  background: #f5f5f5;
  z-index: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.0/anime.min.js"></script>
<div class="text-animation">
  Welcome to codingflag
</div>

Answer №2

If you're looking for a simple and user-friendly solution, I suggest checking out Typed.js. It's incredibly easy to use and can be implemented quickly. Here's an example showcasing the power of Typed.js:

Take a look at this demonstration:

var typed = new Typed('#text', {
    strings: ["First String..!","Second String..!","Third String..!","Third Word..!"],
    typeSpeed: 120,
    backSpeed: 80,
    loop: true
 });
body{
  padding:0;
  margin:0;
  box-sizing:border-box;
}
.container{
  background-image: linear-gradient(to right top, #051937, #004d7a, #008793, #00bf72, #a8eb12);
  width:100vw;
  height:100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
h2{
  text-align:center;
  color:white;
}
<!--Typed.js CDN-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/typed.js/2.0.5/typed.min.js"></script>

<!--Body-->
<div class="container">
  <h2 id="text"></h2>
</div>


Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing Conditional Attribute Addition in Vue.js

When developing in vue, I encountered this scenario: <v-dialog v-model="data_table.dialog"> I have a variable called is_mobile that is observable. My goal is to modify the tag above based on the value of is_mobile. For instance: <v-dialog v-mod ...

Obtaining the Camera's Position Relative to the Origin in Three.js

The wording of this question might be unclear, but I'm struggling to phrase it concisely. Here's the scenario: there is a perspective camera in the scene along with a mesh. The mesh is positioned away from the origin of the axis. The camera is ...

transmit information and documents to server using Axios

I am working on a project using ReactJs and I need to send data to a Laravel API using Axios. Here is the code snippet I have tried: export const send = (data, File) => { const formData = new FormData(); formData.append('media', File); ...

Conceal and reveal button with every tap

I have a scenario with 2 buttons. One button is 'disable' in one case and 'enable' in another case, but there is also a button that does not show due to the style display: none. I am using jQuery in this scenario. When I click on the e ...

Strategies for including JavaScript variables in AJAX data

I have a basic webpage displaying employee names that can be dragged around using Jquery UI draggable. I am able to capture the "top" and "left" position of the dragged item and store it in a JavaScript variable. My next goal is to pass these two variable ...

How to eliminate space preceding a div using jQuery?

I am trying to modify the following code snippet: <div id="one">1</div> <div id="two">2</div> <div id="three">3</div> Is there a method for me to eliminate the space before div "three" in order to achieve this result: ...

Which is better: CSS gradients or background images?

Years ago, I came across many CSS codes that used background-image: url(xxx.png) to mimic a gradient background filter, as only (please correct me if I'm mistaken) IE's proprietary filter could achieve a CSS gradient. In today's world - giv ...

Use the @PostMapping annotation and remain on the current page without being redirected

I'm currently utilizing Spring Boot for my project. I have a page that displays all ads, and I am in need of adding ads to favorites without redirecting or reloading the page. Essentially, I want users to be able to click on a button to add an ad to t ...

Is it better to process data in a React app using Express or handle it directly on the front end with React?

Hey there, I need some advice on how to create a league table for my application. The JSON data structure is set up like this: I'm considering whether to calculate each player's league data on the front-end using React by looping through the fixt ...

Updating data in MySQL using Node.js

I've been working on implementing a feature to update user information in a MySQL database. However, I'm facing an issue where Postman doesn't seem to be reading the ID, username, and email correctly. While I successfully implemented login a ...

Retain the updated select values even when the back button is pressed

My form allows users to filter through different cars with ease and efficiency. When a user selects a "Make," the corresponding "Models" populate in the next dropdown seamlessly. However, an issue arises when a user performs a search and then clicks the ...

Vue.js: Utilizing anonymous functions within props object

Looking to enhance the select2 example to make it more practical, I have added multiselect functionality and am now exploring custom select2 configuration options. Check out my progress on jsFiddle Encountering an issue where function properties of props ...

The MaterialUI FormControl API TextField is experiencing an issue where the onClick event does not trigger on the initial click

I am currently working on a React application where I have integrated a MaterialUI Form Control API TextField. However, I am facing an issue with the Select tag as the onClick method is only firing after the first click. There are no hidden CSS properties ...

Experience the click action that comes equipped with two unique functions: the ability to effortlessly add or remove a class

Currently, I am in the process of creating a list of anchor links that contain nested anchor links, and there are a few functionalities that I am looking to implement. Upon clicking on a link: Add a class of "current" Remove the class of "current" from ...

Missing Back Button Feature in jQuery Mobile Interface

Looking for some help with this code snippet: http://jsfiddle.net/dGJEH/ Can anyone explain why the back button is no longer visible? This is how my page is currently structured: <div data-role="page" id="details" data-add-back-btn="true" data-back- ...

Having trouble with CORS errors persisting despite configuring CORS options for Google Authentication on React/Node/Passport

Currently, I'm in the process of developing a basic application using React for the frontend and Node/Express/MongoDB for the backend. User authentication is being handled through Passport, with local authentication and Google authentication both func ...

Link social media buttons to specific posts

I've developed my own PHP blog from scratch. The homepage showcases all the latest posts. I integrated Facebook Like and Tweet buttons beneath the title of each post, but they are currently functioning for the entire homepage instead of each specific ...

The code snippet 'onload='setInterval("function()",1000)' is not functioning as expected

I need to continuously load the contents of an XML file into a specific HTML div every second. Here is the JavaScript code that I am using to parse the XML file: function fetchEntries() { if (window.XMLHttpRequest) req = new XMLHttpRequest(); ...

Attempting to modify text using the header parameter has proven to be ineffective

pages/_middleware.ts import { NextRequest, NextResponse } from 'next/server'; const isMobile = (userAgent: string) => /iPhone|iPad|iPod|Android/i.test(userAgent); const propName = 'x-rewrite'; enum Device { desktop = 'no& ...

Showing information from a SQL database in an HTML format

The PHP code below is used to retrieve data from a MySQL table, but I need assistance in displaying it in an HTML form. <?php $servername = "localhost"; $username = "root"; $password = "icsk"; $dbname = "yusuf"; // Create connection $conn = new mysqli ...