Require Assistance With Creating a Typing Animation in JavaScript?

Recently, I created a JavaScript text typer code:

Here is the CSS:

body 
{
    background-color: black;
}

#writer
{ 
    font-family: Courier;
    font-size: 12px;
    color: #24FF00;
    background-color: black;
}

And here is the JavaScript:

var text = "Help Please, I want help.";
var counter = 0;
var speed = 25;

function type()
{
    lastText = document.getElementById("writer").innerHTML;
    lastText += text.charAt(counter);
    counter++;
    document.getElementById("writer").innerHTML = lastText;
}

setInterval(function(){type()}, speed);

Lastly, let's take a look at the HTML:

<div id="writer"></div>

However, I am struggling to use the <br> tag to move to a new line in the typed text. No matter what I try, it doesn't seem to work. For instance, when typing "My name is Master M1nd.", how can I go to a new line after that?

Answer №1

If you're looking to simplify things, I've created a jQuery plugin that might be helpful for you. Take a look at the live demo here: http://jsfiddle.net/wared/V7Tv6/. In the demo, you'll see jQuery being loaded through the first <script> tag. You can follow the same pattern for other <script> tags if desired—while not mandatory, it's generally good practice. Simply place the code inside individual files and set the appropriate src attributes in this order:

<script src=".../jquery.min.js"></script>
<script src=".../jquery.marquee.js"></script>
<script src=".../init.js"></script>

⚠ Please note: This has only been tested with Chrome ⚠

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
jQuery.fn.marquee = function($) {

    function findTextNodes(node) {
        var result = [],
            i = 0,
            child;
        while (child = node.childNodes[i++]) {
            if (child.nodeType === 3) {
                result.push(child);
            } else {
                result = result.concat(
                    findTextNodes(child)
                );
            }
        }
        return result;
    }

    function write(node, text, fn) {
        var i = 0;
        setTimeout(function() {
            node.nodeValue += text[i++];
            if (i < text.length) {
                setTimeout(arguments.callee, 50);
            } else {
                fn();
            }
        }, 50);
    }

    return function(html) {
        var fragment, textNodes, text;
        fragment = $('<div>' + html + '</div>');
        textNodes = findTextNodes(fragment[0]);
        text = $.map(textNodes, function(node) {
            var text = node.nodeValue;
            node.nodeValue = '';
            return text;
        });
        this.each(function() {
            var clone = fragment.clone(),
                textNodes = findTextNodes(clone[0]),
                i = 0;
            $(this).append(clone.contents());
            (function next(node) {
                if (node = textNodes[i]) {
                    write(node, text[i++], next);
                }
            })();
        });
        return this;
    };
}(jQuery);
</script>
<script>
jQuery(function init($) {

    var html = 'A <i>marquee</i> which handles <u><b>HTML</b></u>,<br/> only tested with Chrome. <a href="#">Replay</a>';
    $('p').marquee(html);

    $('a').click(function(e) {
        e.preventDefault();
        $('p').empty();
        $('a').off('click');
        init($);
    });
});

</script>
<p></p>
<p></p>

Answer №2

One way to improve efficiency is by using \n instead of passing <br> character by character and then converting it back to <br> when modifying the innerHTML.

Here's an example (http://jsfiddle.net/qZ4u9/1/):

function escape(c) {
    return (c === '\n') ? '<br>' : c;
}

function writer(text, out) {
    var current = 0;
    return function () {
        if (current < text.length) {
            out.innerHTML += escape(text.charAt(current++));
        }
        return current < text.length;
    };
}

var typeNext = writer('Hello\nWorld!', document.getElementById('writer'));

function type() {
    if (typeNext()) setInterval(type, 500);
}

setInterval(type, 500);

You may also want to consider exploring requestAnimationFrame for your typing animation (). It could enhance the smoothness of your animation :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Choosing the appropriate data type for form data on the server

Seeking assistance on uploading an audio file to my server using the following method: var fd = new FormData(); fd.append('fname', 'test.wav'); fd.append('data', soundBlob); $.ajax({ type: 'POST', url: &apos ...

Can you explain the significance of the $ symbol in the context of this jQuery function?

How are the two functions different in terms of jQuery usage? Question: What is the significance of $ in this example? JS: jQuery(document).ready(function() { console.log('loaded'); }); jQuery(document).ready(function($) { console.lo ...

In Angular 15, CSS override configurations do not function as intended

Exploring the world of Angular is exciting, and I am a newcomer to it. Currently, I am tackling an innovative Angular 15 project that makes use of the Material library. My current predicament lies in the fact that none of the CSS overrides appear to be tak ...

jQuery UI's $(...).sortable function is throwing an error when being used with WebPack

After setting up everything correctly, I encountered an unusual issue with Webpack. Let's take a look at this simple app.ts file: 'use strict'; import $ = require('jquery'); import 'jquery-ui'; $(function() { $( " ...

Amusing antics observed when hovering over a div in Firefox

Issue resolved, many thanks to all Here is the dilemma I am dealing with something like this <a href='http://google.com' class="buy_now" > <div class='yada yada' > Go </div> </a> buy_now changes backgro ...

Is there a solution for passing multiseries data in JSON that works with AnyChart in ReactJS since the standard method is not functioning correctly?

I need help implementing a column chart using AnyChart in react with multi-series data. Below is a sample JSON structure that I am having trouble passing to the chart. const multiSeriesSettings = { width: 800, height: 600, type: "column", ...

Here's a tip on how to trigger a function when the text in an input box changes using JavaScript

While using Vue, I am developing a form which includes an input box. Whenever the text in the input box changes, it should update the function setMessage. <input type="text" v-model="test" v-on:change"setMessage"> However, the issue is that the upd ...

Display a placeholder if image source is not working or missing

Looking to display a logo in next.js, my plan is to show a span if the logo is not available and hide it if it is. <div className='brand'> <Link href="#"> <img src="#" alt="UnSet" /> <s ...

Obtain data from files within a React frontend application

I have integrated an API endpoint into my NodeJS application. The purpose of this endpoint is to locate a specific file in a folder based on the filename provided in the request. Here's how I am approaching this: const fileDirectory = 'C:/Sites/p ...

Enhancing Jquery: Creating Partial Renderings

I've been working on a new function to extend jquery. It seems to be functioning properly, but I encountered an error when testing it out. XMLHttpRequest cannot load file:.../WebstormProjects/JQuery.FormHelpers/_partial.html. Origin null is not all ...

Why are the icon and text aligned on the same row?

I'm trying to display an icon next to some text on the same line, but it seems to only work when using the <div> tag. When I try to do the same with the <p> tag, it doesn't align properly. Can someone explain why? .container { di ...

Both of the radio buttons in Material-UI have been selected

I have a unique document that showcases an implementation of RadioGroup, FormControlLabel, and FormControl. Take a look at the code snippet below for reference. import React from 'react'; import PropTypes from 'prop-types'; import Radio ...

Collecting Information from the DOM to Append to an Array with JavaScript

My aim is to create a fully functional shopping cart using either vanilla JavaScript or jQuery. I'm uncertain if I'm approaching it the right way, but here's my plan: Firstly, I want to establish an array named cartItems to store all sho ...

A step-by-step guide on implementing styled components in React.js with conditional statements

Embarking on my latest project with the goal of going "from Zero to Hero", I received a tip from a friend about styled components. Intrigued, I decided to ditch my traditional .css files and make the switch. Although I understand the basics - using <My ...

Organizing an intricate collection of objects based on a true/false property in JavaScript

I have been searching for solutions to this issue, but unfortunately nothing seems to be working for me. My problem involves a large array of objects that I need to sort based on a boolean property (with all the true values taking precedence). The common ...

Error 56 EROFS encountered when trying to save a file in Node.js filesystem every 2 seconds

I've set up a node.js environment on my raspbian system and I'm attempting to save/update a file every 2/3 seconds using the code below: var saveFileSaving = false; function loop() { mainLoop = setTimeout(function() { // update data ...

Issue with making Flickr API request using XMLHttpRequest receiving an unsuccessful response

I'm having issues trying to retrieve a JSON list from Flickr using plain JavaScript and XMLHttpRequest. Here is an example of an AJAX call without a callback function that is not functioning properly: var url = "https://api.flickr.com/services/feed ...

Adding space between Bootstrap columns to align them one below the other on small devices

https://i.sstatic.net/turhY.png Within this illustration, there are two columns - one with the class col-sm-3 and the other with col-sm-8, situated in a single row. Upon resizing the window (as shown in the screenshot provided), the two columns appear ...

Determine the presence of a Facebook user by using JavaScript

I am trying to find a method to verify the existence of a Facebook user based on their ID. As far as I understand, there is a Graph API that can provide a Facebook user's profile picture using their ID in this format: I have noticed that if an inval ...

`How can I stop typescript from converting dynamic imports to require()?`

Currently, I am in the process of creating a Discord bot using discord.js. Interestingly, discord.js does not seem to be compatible with ESM modules, which has been causing some complications in my project. As a result, I have resorted to utilizing CommonJ ...