JavaScript Typewriter Effect

Web Design & Web Development

Demo

Sponsored links

 

Code

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>JavaScript Typewriter Effect</title>
    <link rel="stylesheet" type="text/css" href="https://demo.plantpot.works/assets/css/normalize.css">
    <link rel="stylesheet" href="https://use.typekit.net/opg3wle.css">
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="typewriter.js"></script>
  </head>
  <body>
    <div id="container">
      <div class="box">
        <div id="text" class="text"></div>
        <span id="caret" class="caret"></span>
      </div>
    </div>
  </body>
</html>

CSS

@charset "utf-8";
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
html {
  font-size: 16px;
}
body {
  background-color: #000;
  font-family: futura-pt, sans-serif;
  -webkit-tap-highlight-color: rgba(0,0,0,0);
}
#container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100vh;
}
.box {
  position: relative;
  height: 50px;
  padding: 0 8px;
}
.text {
  color: #fff;
  font-size: 2.75rem;
  letter-spacing: 1px;
}
.caret {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 1px;
  height: 100%;
  background-color: #fff;
}
.blink {
  animation: anime 1s steps(1) infinite;
}
@keyframes anime {
  50% {
    opacity: 0;
  }
}
@media screen and (max-width: 480px) {
  .box {
    height: 23px;
    padding: 0 4px;
  }
  .text {
    font-size: 1.25rem;
  }
}

JavaScript

var i = 0;
var str = sourceStr = 'JavaScript Typewriter Effect.';
var flg = 0;

function typeWriter() {
  stopBlink();
  if (i < str.length) {
    document.getElementById("text").innerHTML += str.charAt(i);
    i++;
    setTimeout(typeWriter, 100);
  } else if (i == str.length && flg == 0) {
    startBlink();
    setTimeout(typeWriter, 2000);
    flg = 1;
  } else if (i > 0) {
    document.getElementById("text").innerHTML = str = str.slice( 0, -1);
    i--;
    setTimeout(typeWriter, 100);
  } else {
    str = sourceStr;
    startBlink();
    setTimeout(typeWriter, 2000);
    flg = 0;
  }
}
function startBlink() {
  document.getElementById("caret").classList.add("blink");
}
function stopBlink() {
  document.getElementById("caret").classList.remove("blink");
}
window.onload = function() {
  startBlink();
  setTimeout(typeWriter, 2000);
}