JavaScriptでタイピングエフェクト


実装の流れ

・HTMLで要素の設置。
・JavaScriptで文字列を一文字ずつタイピング風に出力する。
・CSSアニメーションと擬似要素でカーソルをつける。

HTMl

index.html
<h2 id="js-typewriter" class="hero__title"></h2>

JavaScript

・文字列を出力する要素を指定する
・タイピング風に表示する文字列を指定する
・文字列を出力する要素を取得する
・文字列を一文字ずつ分割して配列に格納する
・配列内の文字を一定の秒間隔で一文字ずつ指定要素に出力する

split()で文字列を一文字ずつ分割して、分割した文字列をsetTimeout()で時間をずらして要素に入れる。

type.js
const typewriter = (param) => {
  let el = document.querySelector(param.el);
  let speed = param.speed;
  let string = param.string.split("");

   window.setTimeout(function () {
      string.forEach((char, index) => {
        setTimeout(() => {
          el.textContent += char;
        }, speed * index);
    });
  }, 500);
};

typewriter({
  el: "#js-typewriter", //要素
  string: "タイピング風に文字が出力されます。", //文字
  speed: 80 //速度
});

CSSアニメーション

animation-delay:;を使って文字を出力し切った後からアニメーションを発生させるとよりリアリティ増します。

style.scss
.hero__title {
  &::after {
    content: "|";
    animation-name: typing;
    animation-duration: 1s;
    animation-iteration-count: infinite;
    animation-delay: 4s;
  }
}

@keyframes typing {
  from {
      opacity: 0;
  }
  to {
      opacity: 1;
  }
}