Creating a Typewriter Effect in JavaScript

The typewriter effect is a classic and engaging way to display text dynamically on a web page. In this blog, we’ll discuss how to create a typewriter effect using HTML, CSS, and JavaScript. We’ll also explore how we can enhance it with styling and sound effects, as shown in the provided code.


Overview of the Code

The typewriter effect in this example displays text character by character, mimicking the behavior of typing on a typewriter. Additionally, a blinking cursor and background sound enhance the effect.


Step-by-Step Breakdown

1. HTML Structure

The HTML defines the structure of the typewriter effect.

  • <div id="typewriter">: This is the container where the typewriter text appears dynamically.
  • <span class="cursor">: A blinking cursor element styled using CSS animations.
  • <audio>: An optional audio element for background typing sounds.
<div class="container">
  <div id="typewriter"></div><span class="cursor"></span>
</div>
<audio id="aud" controls autoplay>
  <source src="./typing.mp3" type="audio/mpeg">
</audio>

2. CSS for Styling

The CSS provides styling and animations for the typewriter effect:

  • Background and Font Styling: body { background-color: #e94e1b; color: white; font-family: "Courier New", Courier, monospace; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; } .container { font-size: 1.2rem; line-height: 1.6; }
  • Cursor Animation: A blinking cursor is implemented using the @keyframes rule. .cursor { display: inline-block; width: 2px; height: 1em; background-color: white; animation: blink 0.6s step-end infinite; } @keyframes blink { from { background-color: white; } to { background-color: transparent; } }

3. JavaScript for the Typewriter Effect

The logic for the typewriter effect resides in the script.

  • Defining the Text: The text variable contains the text to be displayed, including line breaks (\n). const text = `# Program to count occurrences of an element using the count() method numbers = [1, 2, 3, 4, 2, 2, 5, 6, 2] count = numbers.count(2) print("The number 2 appears", count, "times in the list.")`;
  • Typewriter Function: The typeWriter function adds one character at a time to the #typewriter element. function typeWriter() { if (i < text.length) { if (text.charAt(i) === "\n") { typewriterElement.innerHTML += "<br>"; } else { typewriterElement.innerHTML += text.charAt(i); } i++; setTimeout(typeWriter, speed); // Recursive call to simulate typing } }
  • Start the Effect: The typeWriter function is called to initiate the typing process. typeWriter();

Enhancements

  1. Typing Sound Effect: An audio file (typing.mp3) is played automatically when the page loads. To keep it optional, you can hide the audio controls using CSS: #aud { display: none; }
  2. Customizable Speed: Modify the speed variable to adjust the typing speed: const speed = 50; // Milliseconds
  3. Dynamic Text: To make the typewriter effect dynamic, you can fetch text from an API or user input.

Complete Code

Here’s the complete code for reference:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Typewriter Effect</title>
  <style>
    body {
      background-color: #e94e1b;
      color: white;
      font-family: "Courier New", Courier, monospace;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      margin: 0;
    }

    .container {
      font-size: 1.2rem;
      line-height: 1.6;
    }

    .cursor {
      display: inline-block;
      width: 2px;
      height: 1em;
      background-color: white;
      animation: blink 0.6s step-end infinite;
    }

    #aud {
        display: none;
    }

    @keyframes blink {
      from {
        background-color: white;
      }
      to {
        background-color: transparent;
      }
    }
  </style>
</head>
<body>
    <audio id="aud" controls autoplay>
        <source src="./typing.mp3" type="audio/mpeg">
    </audio>
  <div class="container">
    <div id="typewriter"></div><span class="cursor"></span>
  </div>

  <script>
    const text = `# Program to count occurrences of an element using the count() method
    numbers = [1, 2, 3, 4, 2, 2, 5, 6, 2]
    count = numbers.count(2)
    print("The number 2 appears", count, "times in the list.")`;

    const typewriterElement = document.getElementById("typewriter");
    let i = 0;
    const speed = 50;

    function typeWriter() {
      if (i < text.length) {
        if (text.charAt(i) === "\n") {
          typewriterElement.innerHTML += "<br>";
        } else {
          typewriterElement.innerHTML += text.charAt(i);
        }
        i++;
        setTimeout(typeWriter, speed);
      }
    }
    typeWriter();
  </script>
</body>
</html>

Conclusion

This typewriter effect is a visually appealing way to present text dynamically. By combining JavaScript for logic, CSS for styling, and optional sound effects, you can create engaging web experiences. Experiment with different texts, speeds, and styles to customize it for your project!


Share with our team

Leave a Comment