Home  >  Article  >  Web Front-end  >  How can I create a typewriter effect for text in my HTML using CSS and JavaScript?

How can I create a typewriter effect for text in my HTML using CSS and JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-25 03:50:29893browse

How can I create a typewriter effect for text in my HTML using CSS and JavaScript?

Displaying Text One Character at a Time

Problem:

Enhance the elegance of displaying an HTML text letter by letter, akin to videogame captions, utilizing CSS and JavaScript.

Solution:

To achieve this effect, a harmonious combination of JavaScript and CSS can be employed. Splitting the text into characters and appending them sequentially with JavaScript ensures letter-by-letter revelation.

HTML:

<div id="msg"></div>

JavaScript:

function showText(target, message, index, interval) {
  if (index < message.length) {
    $(target).append(message[index++]);
    setTimeout(() => { showText(target, message, index, interval); }, interval);
  }
}

Usage:

$(function () {
  showText("#msg", "Hello, World!", 0, 500);
});

This solution gracefully handles inner HTML content, enhancing the text display experience.

The above is the detailed content of How can I create a typewriter effect for text in my HTML using CSS and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn