TypeWriter Effect in css and JS

Here’s a simple typewriter effect using HTML, CSS, and JavaScript, which types and re-types the sentences one after another like:

Here’s a simple typewriter effect using HTML, CSS, and JavaScript, which types and re-types the sentences one after another like:

  • You Learn the Next
  • You UpSkill the Next
  • You Innovate the Next

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Typewriter Effect</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="typewriter-container">
    <span>You </span><span class="typed-text"></span><span class="cursor">|</span>
  </div>

  <script src="script.js"></script>
</body>
</html>

CSS (style.css)

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #0e0e0e;
  color: white;
  font-family: 'Courier New', Courier, monospace;
  font-size: 2rem;
}

.typewriter-container {
  display: inline;
}

.cursor {
  display: inline-block;
  width: 2px;
  background-color: white;
  animation: blink 0.7s infinite;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}

JavaScript (script.js)

const textArray = ["Learn the Next", "UpSkill the Next", "Innovate the Next"];
const typingDelay = 100;
const erasingDelay = 50;
const newTextDelay = 1500; // Delay between texts
let textIndex = 0;
let charIndex = 0;

const typedTextSpan = document.querySelector(".typed-text");

function type() {
  if (charIndex < textArray[textIndex].length) {
    typedTextSpan.textContent += textArray[textIndex].charAt(charIndex);
    charIndex++;
    setTimeout(type, typingDelay);
  } else {
    setTimeout(erase, newTextDelay);
  }
}

function erase() {
  if (charIndex > 0) {
    typedTextSpan.textContent = textArray[textIndex].substring(0, charIndex - 1);
    charIndex--;
    setTimeout(erase, erasingDelay);
  } else {
    textIndex++;
    if (textIndex >= textArray.length) textIndex = 0;
    setTimeout(type, typingDelay);
  }
}

document.addEventListener("DOMContentLoaded", () => {
  setTimeout(type, newTextDelay);
});

🪄 How It Works

  • CSS styles the text and creates a blinking cursor.
  • JavaScript types each phrase one letter at a time, then erases it, then moves to the next.
  • Loop repeats through all the phrases in textArray.

You |

Post a Comment

Previous Post Next Post