찾다
웹 프론트엔드CSS 튜토리얼당신이 던지는 모든 것을 처리하는 타이핑 라이터 애니메이션

Typewriter Animation That Handles Anything You Throw at It

I watched Kevin Powell’s video where he was able to recreate a nice typewriter-like animation using CSS. It’s neat and you should definitely check it out because there are bonafide CSS tricks in there. I’m sure you’ve seen other CSS attempts at this, including this site’s very own snippet.

Like Kevin, I decided to recreate the animation, but open it up to JavaScript. That way, we have a few extra tools that can make the typing feel a little more natural and even more dynamic. Many of the CSS solutions rely on magic numbers based on the length of the text, but with JavaScript, we can make something that’s capable of taking any text we throw at it.

So, let’s do that. In this tutorial, I’m going to show that we can animate multiple words just by changing the actual text. No need to modify the code every time you add a new word because JavaScript will do that for you!

Starting with the text

Let’s start with text. We are using a monospace font to achieve the effect. Why? Because each character or letter occupies an equal amount of horizontal space in a monospaced font, which will come handy when we’ll use the concept of steps() while animating the text. Things are much more predictable when we already know the exact width of a character and all characters share the same width.

We have three elements placed inside a container: one element for the actual text, one for hiding the text, and one for animating the cursor.

<div>
  <div></div>
  <div>Typing Animation</div>
  <div></div>
</div>

We could use ::before and ::after pseudo-elements here, but they aren’t great for JavaScript. Pseudo-elements are not part of the DOM, but instead are used as extra hooks for styling an element in CSS. It’d be better to work with real elements.

We’re completely hiding the text behind the .text_hide element. That’s key. It’s an empty div that stretches the width of the text and blocks it out until the animation starts—that’s when we start to see the text move out from behind the element.

In order to cover the entire text element, position the .text_hide element on top of the text element having the same height and width as that of the text element. Remember to set the background-color of the .text_hide element exactly same as that of the background surrounding the text so everything blends in together.

.container {
  position: relative;
}
.text {
  font-family: 'Roboto Mono', monospace;
  font-size: 2rem;
}
.text_hide {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
}

The cursor

Next, let’s make that little cursor thing that blinks as the text is being typed. We’ll hold off on the blinking part for just a moment and focus just on the cursor itself.

Let’s make another element with class .text_cursor. The properties are going to be similar to the .text_hide element with a minor difference: instead of setting a background-color, we will keep the background-color transparent (since its technically unnecessary, then add a border to the left edge of the new .text_cursor element.

.text_cursor{
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: transparent;
  border-left: 3px solid black;
}

Now we get something that looks like a cursor that’s ready to move as the text moves:

JavaScript animation

Now comes the super fun part—let’s animate this stuff with JavaScript! We’ll start by wrapping everything inside a function called typing_animation().

function typing_animation(){
  // code here
}
typing_animation();

Next task is to store each and every character of text in a single array using the split() method. This divides the string into a substring that has only one character and an array containing all the substrings is returned.

function typing_animation(){
  let text_element = document.querySelector(".text");
  let text_array = text_element.innerHTML.split("");
}

For example, if we take “Typing Animation” as a string, then the output is:

We can also determine the total number of characters in the string. In order to get just the words in the string, we replace split("") with split(" "). Note that there is a difference between the two. Here, " " acts as a separator. Whenever we encounter a single space, it will terminate the substring and store it as an array element. Then the process goes on for the entire string.

function typing_animation(){
  let text_element = document.querySelector(".text");
  let text_array = text_element.innerHTML.split("");
  let all_words = text_element.innerHTML.split(" ");
}

For example, for a string ‘Typing Animation’, the output will be,

Now, let’s calculate the length of the entire string as well as the length of each and every individual word.

function typing_animation() {
  let text_element = document.querySelector(".text");
  let text_array = text_element.innerHTML.split("");
  let all_words = text_element.innerHTML.split(" ");
  let text_len = text_array.length;

  const word_len = all_words.map((word) => {
    return word.length;
  });
}

To get the length of the entire string, we have to access the length of the array containing all the characters as individual elements. If we’re talking about the length of a single word, then we can use the map() method, which accesses one word at a time from the all_words array and then stores the length of the word into a new array called word_len. Both the arrays have the same number of elements, but one contains the actual word as an element, and the other has the length of the word as an element.

Now we can animate! We’re using the Web Animation API because we’re going with pure JavaScript here—no CSS animations for us in this example.

First, let’s animate the cursor. It needs to blink on and off infinitely. We need keyframes and animation properties, both of which will be stored in their own JavaScript object. Here are the keyframes:

document.querySelector(".text_cursor").animate([
  {
    opacity: 0
  },
  {
    opacity: 0, offset: 0.7
  },
  {
    opacity: 1
  }
], cursor_timings);

We have defined three keyframes as objects which are stored in an array. The term offset: 0.7 simply means that after 70% completion of the animation, the opacity will transition from 0 to 1.

Now, we have to define the animation properties. For that, let’s create a JavaScript object that holds them together:

let cursor_timings = {
  duration: 700, // milliseconds (0.7 seconds)
  iterations: Infinity, // number of times the animation will work
  easing: 'cubic-bezier(0,.26,.44,.93)' // timing-function
}

We can give the animation a name, just like this:

let animation = document.querySelector(".text_cursor").animate([
  // keyframes
], //properties);

Here’s a demo of what we have done so far:

Great! Now, let’s animate the .text_hide element that, true to its name, hides the text. We define animation properties for this element:

let timings = {
  easing: `steps(${Number(word_len[0])}, end)`,
  delay: 2000, // milliseconds
  duration: 2000, // milliseconds
  fill: 'forwards'
}

The easing property defines how the rate of animation will change over time. Here, we have used the steps() timing function. This animates the element in discrete segments rather than a smooth continuous animation—you know, for a more natural typing movement. For example, the duration of the animation is two seconds, so the steps() function animates the element in 9 steps (one step for each character in “Animation”) for two seconds, where each step has a duration of 2/9 = 0.22 seconds.

The end argument makes the element stay in its initial state until the duration of first step is complete. This argument is optional and its default value is set to end. If you want an in-depth insight on steps(), then you can refer this awesome article by Joni Trythall.

The fill property is the same as animation-fill-mode property in CSS. By setting its value to forwards, the element will stay at the same position as defined by the last keyframe after the animation gets completed.

Next, we will define the keyframes.

let reveal_animation_1 = document.querySelector(".text_hide").animate([
  { left: '0%' },
  { left: `${(100 / text_len) * (word_len[0])}%` }
], timings);

Right now we are animating just one word. Later, we will see how to animate multiple words.

The last keyframe is crucial. Let’s say we want to animate the word “Animation.” Its length is 9 (as there are nine characters) and we know that it’s getting stored as a variable thanks to our typing_animation() function. The declaration 100/text_len results to 100/9, or 11.11%, which is the width of each and every character in the word “Animation.” That means the width of each and every character is 11.11% the width of the entire word. If we multiply this value by the length of the first word (which in our case is 9), then we get 100%. Yes, we could have directly written 100% instead of doing all this stuff. But this logic will help us when we are animating multiple words.

The result of all of this is that the .text_hide element animates from left: 0% to left: 100%. In other words, the width of this element decreases from 100% to 0% as it moves along.

We have to add the same animation to the .text_cursor element as well because we want it to transition from left to right along with the .text_hide element.

Yayy! We animated a single word. What if we want to animate multiple words? Let’s do that next.

Animating multiple words

Let’s say we have two words we want typed out, perhaps “Typing Animation.” We animate the first word by following the same procedure we did last time. This time, however, we are changing the easing function value in the animation properties.

let timings = {
  easing: `steps(${Number(word_len[0] + 1)}, end)`,
  delay: 2000,
  duration: 2000,
  fill: 'forwards'
}

We have increased the number by one step. Why? Well, what about a single space after a word? We must take that into consideration. But, what if there is only one word in a sentence? For that, we will write an if condition where, if the number of words is equal to 1, then steps(${Number(word_len[0])}, end). If the number of words is not equal to 1, then steps(${Number(word_len[0] + 1)}, end).

function typing_animation() {
  let text_element = document.querySelector(".text");
  let text_array = text_element.innerHTML.split("");
  let all_words = text_element.innerHTML.split(" ");
  let text_len = text_array.length;
  const word_len = all_words.map((word) => {
    return word.length;
  })
  let timings = {
    easing: `steps(${Number(word_len[0])}, end)`,
    delay: 2000,
    duration: 2000,
    fill: 'forwards'
  }
  let cursor_timings = {
    duration: 700,
    iterations: Infinity,
    easing: 'cubic-bezier(0,.26,.44,.93)'
  }
  document.querySelector(".text_cursor").animate([
    {
      opacity: 0
    },
    {
      opacity: 0, offset: 0.7
    },
    {
      opacity: 1
    }
  ], cursor_timings);
  if (all_words.length == 1) {
    timings.easing = `steps(${Number(word_len[0])}, end)`;
    let reveal_animation_1 = document.querySelector(".text_hide").animate([
      { left: '0%' },
      { left: `${(100 / text_len) * (word_len[0])}%` }
    ], timings);
    document.querySelector(".text_cursor").animate([
      { left: '0%' },
      { left: `${(100 / text_len) * (word_len[0])}%` }
    ], timings);
  } else {
    document.querySelector(".text_hide").animate([
      { left: '0%' },
      { left: `${(100 / text_len) * (word_len[0] + 1)}%` }
    ], timings);
    document.querySelector(".text_cursor").animate([
      { left: '0%' },
      { left: `${(100 / text_len) * (word_len[0] + 1)}%` }
  ], timings);
  }
}
typing_animation();

For more than one word, we use a for loop to iterate and animate every word that follows the first word.

for(let i = 1; i 



<p>Why did we take i = 1? Because by the time this for loop is executed, the first word has already been animated.</p>



<p>Next, we will access the length of the respective word:</p>



<pre rel="JavaScript" data-line="">for(let i = 1; i 



<p>Let’s also define the animation properties for all words that come after the first one.</p>



<pre rel="JavaScript" data-line="">// the following code goes inside the for loop
let timings_2 = {
  easing: `steps(${Number(single_word_len + 1)}, end)`,
  delay: (2 * (i + 1) + (2 * i)) * (1000),
  duration: 2000,
  fill: 'forwards'
}

The most important thing here is the delay property. As you know, for the first word, we simply had the delay property set to two seconds; but now we have to increase the delay for the words following the first word in a dynamic way.

The first word has a delay of two seconds. The duration of its animation is also two seconds which, together, makes four total seconds. But there should be some interval between animating the first and the second word to make the animation more realistic. What we can do is add a two-second delay between each word instead of one. That makes the second word’s overall delay 2 + 2 + 2, or six seconds. Similarly, the total delay to animate the third word is 10 seconds, and so on.

The function for this pattern goes something like this:

(2 * (i + 1) + (2 * i)) * (1000)

…where we’re multiplying by 1000 to convert seconds to milliseconds.

The longer the word, the faster it is revealed. Why? Because the duration remains the same no matter how lengthy the word is. Play around with the duration and delay properties to get things just right.

Remember when we changed the steps() value by taking into consideration a single space after a word? In the same way, the last word in the sentence doesn’t have a space after it, and thus, we should take that into consideration in another if statement.

// the following code goes inside the for loop
if (i == (all_words.length - 1)) {
  timings_2.easing = `steps(${Number(single_word_len)}, end)`;
  let reveal_animation_2 = document.querySelector(".text_hide").animate([
    { left: `${left_instance}%` },
    { left: `${left_instance + ((100 / text_len) * (word_len[i]))}%` }
  ], timings_2);
  document.querySelector(".text_cursor").animate([
    { left: `${left_instance}%` },
    { left: `${left_instance + ((100 / text_len) * (word_len[i]))}%` }
  ], timings_2);
} else {
  document.querySelector(".text_hide").animate([
    { left: `${left_instance}%` },
    { left: `${left_instance + ((100 / text_len) * (word_len[i] + 1))}%` }
  ], timings_2);
  document.querySelector(".text_cursor").animate([
    { left: `${left_instance}%` },
    { left: `${left_instance + ((100 / text_len) * (word_len[i] + 1))}%` }
  ], timings_2);
}

What’s that left_instance variable? We haven’t discussed it, yet it is the most crucial part of what we’re doing. Let me explain it.

0% is the initial value of the first word’s left property. But, the second word’s initial value should equal the first word’s final left property value.

if (i == 1) {
  var left_instance = (100 / text_len) * (word_len[i - 1] + 1);
}

word_len[i - 1] + 1 refers to the length of the previous word (including a white space).

We have two words, “Typing Animation.” That makes text_len equal 16 meaning that each character is 6.25% of the full width (100/text_len = 100/16) which is multiplied by the length of the first word, 7. All that math gives us 43.75 which is, in fact, the width of the first word. In other words, the width of the first word is 43.75% the width of the entire string. This means that the second word starts animating from where the first word left off.

Last, let’s update the left_instance variable at the end of the for loop:

left_instance = left_instance + ((100 / text_len) * (word_len[i] + 1));

You can now enter as many words as you want in HTML and the animation just works!

Bonus

Have you noticed that the animation only runs once? What if we want to loop it infinitely? It’s possible:

There we go: a more robust JavaScript version of a typewriting animation. It’s super cool that CSS also has an approach (or even multiple approaches) to do the same sort of thing. CSS might even be the better approach in a given situation. But when we need enhancements that push beyond what CSS can handle, sprinkling in some JavaScript does the trick quite nicely. In this case, we added support for all words, regardless of how many characters they contain, and the ability to animate multiple words. And, with a small extra delay between words, we get a super natural-looking animation.

That’s it, hope you found this interesting! Signing off.

위 내용은 당신이 던지는 모든 것을 처리하는 타이핑 라이터 애니메이션의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
@keyframes vs CSS 전환 : 차이점은 무엇입니까?@keyframes vs CSS 전환 : 차이점은 무엇입니까?May 14, 2025 am 12:01 AM

@keyframesandcsstransitionsdifferincomplexity :@keyframesallowsfordeTailEdanimationsections, whilecsStransitsimplestateChanges.UsecsStransitionSforHovereffects likeToncolorChanges 및@keyframesforintricateanimationspinners.

정적 사이트 컨텐츠 관리에 페이지 CMS 사용정적 사이트 컨텐츠 관리에 페이지 CMS 사용May 13, 2025 am 09:24 AM

알고 있습니다. 컨텐츠 관리 시스템 옵션이 수많은 톤을 사용할 수 있으며, 여러 번 테스트했지만 실제로는 아무도 없었습니다. y ' 이상한 가격 책정 모델, 어려운 커스터마이즈, 일부는 전체가되었습니다.

HTML의 CSS 파일 연결에 대한 궁극적 인 안내서HTML의 CSS 파일 연결에 대한 궁극적 인 안내서May 13, 2025 am 12:02 AM

HTML의 일부에서 요소를 사용하여 CSS 파일을 HTML에 연결하면 달성 할 수 있습니다. 1) 태그를 사용하여 로컬 CSS 파일을 연결하십시오. 2) 여러 개의 태그를 추가하여 여러 CSS 파일을 구현할 수 있습니다. 3) 외부 CSS 파일은 다음과 같은 절대 URL 링크를 사용합니다. 4) 파일 경로 및 CSS 파일로드 순서의 올바른 사용을 확인하고 성능을 최적화하면 CSS Preprocessor를 사용하여 파일을 병합 할 수 있습니다.

CSS Flexbox vs Grid : 포괄적 인 검토CSS Flexbox vs Grid : 포괄적 인 검토May 12, 2025 am 12:01 AM

Flexbox 또는 그리드 선택은 레이아웃 요구 사항에 따라 다릅니다. 1) Flexbox는 탐색 표시 줄과 같은 1 차원 레이아웃에 적합합니다. 2) 그리드는 매거진 레이아웃과 같은 2 차원 레이아웃에 적합합니다. 두 사람은 프로젝트에 사용하여 레이아웃 효과를 향상시킬 수 있습니다.

CSS 파일 포함 방법 : 방법 및 모범 사례CSS 파일 포함 방법 : 방법 및 모범 사례May 11, 2025 am 12:02 AM

CSS 파일을 포함시키는 가장 좋은 방법은 태그를 사용하여 HTML 부분에 외부 CSS 파일을 소개하는 것입니다. 1. 태그를 사용하여 외부 CSS 파일을 소개합니다. 2. 작은 조정의 경우 인라인 CSS를 사용할 수 있지만주의해서 사용해야합니다. 3. 대규모 프로젝트는 SASS와 같은 CSS 전 처리기를 사용하여 @Import를 통해 다른 CSS 파일을 가져올 수 있습니다. 4. 성능의 경우 CSS 파일을 병합하고 CDN을 사용해야하고 CSSNANO와 같은 도구를 사용하여 압축해야합니다.

Flexbox vs Grid : 둘 다 배워야합니까?Flexbox vs Grid : 둘 다 배워야합니까?May 10, 2025 am 12:01 AM

예, YoushouldLearnbothflexBoxAndgrid.1) FlexBoxisIdealforone-Dimensional, FlexiblelayoutSlikenavigationMenus.2) GridexCelsIntwo-Dimensional, ComplexDesignsSuchasmagazinElayouts.3) 결합 된 BothenSlayoutFlexibility 및 HeartingFortructur

궤도 역학 (또는 CSS 키 프레임 애니메이션을 최적화하는 방법)궤도 역학 (또는 CSS 키 프레임 애니메이션을 최적화하는 방법)May 09, 2025 am 09:57 AM

자신의 코드를 리팩터링하는 것은 어떤 모습입니까? John Rhea는 자신이 쓴 오래된 CSS 애니메이션을 선택하고 최적화하는 사고 과정을 살펴 봅니다.

CSS 애니메이션 : 만들기가 어렵습니까?CSS 애니메이션 : 만들기가 어렵습니까?May 09, 2025 am 12:03 AM

cssanimationsarenherinly에 hardbutreepracticenderstandingofcsspropertiesandtimingflestions.1) startsimpleants withsimpleatslikeScalingabuttononHoverusingKeyframes.2) useAsingfuctionslikecubic-bezierfornateffects, 그러한 분위기, 3)

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.