Tips for inserting a line break in a script

Hello, I need some assistance with creating a typewriter effect using JS, CSS, and HTML. Everything seems to be working fine except when I try to add a new line of text, it doesn't display properly.

var str = "<p>I want to put text here then another line under this one</p>",
    i = 0,
    isTag,
    text;

(function type() {
    text = str.slice(0, ++i);
    if (text === str) return;
    
    document.getElementById('typewriter').innerHTML = text;

    var char = text.slice(-1);
    if( char === '<' ) isTag = true;
    if( char === '>' ) isTag = false;

    if (isTag) return type();
    setTimeout(type, 80);
}());
#typewriter {
color: lime;
text-align: center;
}
 <div id="typewriter"></div>

Answer №1

let message = "This is a sample\nA bit more text";
let characters = message.split("");
let output = document.getElementById("result");
function display(){
   let char = characters.shift();
   if (char){
       output.innerHTML += char;
       setTimeout(display, 100);
   }
}
display();
<pre id="result"></pre>

Answer №2

employ <br />

let text = "<p>I need to insert text here<br /> then have another line below this one</p>";

Answer №3

One approach is to organize paragraph elements by utilizing span and applying the display style property of span to block.

window.onload = function () {
  var str = "<p><span>I want to put text here then another line under this one</span><span>text here</span></p>";

  (function type(isInTagArg, indexArg) {
    var index = indexArg || 0;
    if (index >= str.length)
      return;

    var isInTag = isInTagArg || false;
    if (isInTag == false) {
      if (str.charAt(index) == '<') {
        return type(true, index + 1);
      } else {
        document.getElementById('typewriter').innerHTML = str.substr(0, index + 1);
      }
    } else {
      if (str.charAt(index) == '>') {
        return type(false, index + 1);
      }
      return type(true, index + 1);
    }
    setTimeout(function() {type(false, index + 1)}, 80);
  }());
}
#typewriter {
  color: lime;
  text-align: center;
}
#typewriter span
{
  display: block;
}
<div id="typewriter"></div>

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

What is the goal of the output file in Webpack?

Currently, I am following the React tutorial at http://www.tutorialspoint.com/reactjs/reactjs_components.htm, and I find myself puzzled about the exact purpose of webpack entry and output filename. In the provided example, they have an index.html file and ...

Adjusting the positioning of elements in a constantly changing scenario

Utilizing Bootstrap, I aim to keep the top-right corner of the red background fixed to the upper right corner of the blue section within the visible area regardless of window resizing due to its responsive design. The red element should be position fixed ...

Using TypeScript with Angular, you can easily include parameters to HTML tags

I have an HTML element that looks like this: eventRender(info){ console.log(info.el); } This is the output I'm seeing: https://i.stack.imgur.com/G0hmw.png Now, I want to include these attributes: tooltip="Vivamus sagittis lacus vel augue ...

Is it possible to use @ViewChild to target an element based on its class name?

The author of this article on Creating Advanced Components demonstrates selecting an element by creating a directive first: @Directive({ selector: '.tooltip-container' }) export class TooltipContainerDirective {} Then, the author uses this d ...

Showing a series of text entries one after the other, each appearing with a smooth fade-in and fade-out

I am eager to showcase a list of text in a sequential order, implementing a fade-in/fade-out effect and concluding with the display of an image. Additionally, I aim to have all the text centered on the page. <div>a<div> <div>b</div> ...

Utilizing Images with 'General Drawing' in Highcharts

I'm currently attempting to create a task diagram using Highcharts. I had the idea of incorporating images using the <img> tag ren.label('<img src="/images/test.jepg', 10, 82) .attr({ ...

What is the best way to incorporate the PUT method...?

Within the realm of programming, there exist three distinct files with specific roles - profiles.model.js, profiles.controller.js, and profiles.router.js. The focus now shifts towards implementing the PUT method across these three files. To begin, profiles ...

The table on the page shifts position when viewed on different devices, sometimes not remaining between the header and footer

Here is a link to see how my page looks with the header, table, and footer: https://i.sstatic.net/U6tdO.png If you want to see how it looks when responsive (with smaller width), check out this link: https://i.sstatic.net/zsGkc.png I have encountered 2 ma ...

Flawlessly Outputting PHP and HTML

When querying a result from a table, I face an issue where the text does not automatically wrap to a new line if it's too long. This results in the text being displayed on a single line and often extending off the page. How can I ensure that the text ...

Observing an element within AngularJS

Struggling to watch an object in AngularJs 2. In a directive, I have an object like this: scope.timelineFilter = {hasCapacity: true, onlyActivated: true, companyIdList: []}; I use 2 JQuery functions to change values of the object (adding a third soon) ...

Utilizing Translation in Ionic Framework for AngularJS Menus

Having integrated Angular NG Translate into my app, I ran into a roadblock when attempting to translate the side menu items. The usual method of using expressions like {{'TEXT1' | translate }} did not work for me due to the format already in use ...

CSS :target activates on hover instead of click

I have a slider that is currently functioning well. However, I am facing a small issue. I would like to change the slider image when hovering over one of the <li> elements, instead of clicking on them. Is this achievable? I came across this referenc ...

How can I float a square to the right in Bootstrap with a col-md-4 size but with a height restricted to only 200 px

Looking to add a small square on the page for users to search and purchase courses directly. The square should be 4 columns wide, follow Bootstrap4 grid template, and be around 200-300 px in length. It needs to remain visible as the user scrolls down the p ...

Transform a JavaScript object array into a collection of individual values

Given a list of objects structured like this, I am looking to transform it into a list of values based on their corresponding IDs. Original = [ {id: 1, value: 12.2494, time: "00:00:00.14"}, {id: 1, value: 4.5141, time: "00:00:01.138"}, {id: 1, ...

What is the best way to retrieve all the keys from an array?

I am looking to retrieve the address, latitude, and longitude data dynamically: let Orders= [{ pedido: this.listAddress[0].address, lat: this.listAddress[0].lat, lng: this.listAddress[0].lng }] The above code only fetches the first item from the lis ...

Encountering a React Runtime issue: The element type is invalid, expecting a string for built-in components or a class/function for composite components

Here is a glimpse of my code: import { React, useState, useEffect } from 'react'; import { GoogleMapReact } from 'google-map-react'; import styles from './Location.module.scss'; import pinstyles from './TheMap.module.scss ...

HTML - Ways to showcase multiple forms on a single row?

I have three forms in my Flask application that I want to display in a single line rather than one after the other. Is there a way to achieve this without using CSS? Here is the HTML snippet: <form action="/pull_entity_by_manufacturer" metho ...

Setting the initial values of state variables upon rendering of a component and using custom hooks

I have a file called Body.jsx that handles fetching data from an API and filtering it. In an attempt to clean up the code, I created a custom hook named useResData specifically for fetching data: export const Body = () => { const resDataList = useResD ...

What's the most efficient method to recursively nest an array of objects into a tree structure with the id serving as a reference point?

My goal is to organize the pages in my database in a hierarchical "tree" view. Each page has a unique ID and a parent property that indicates which page it is a child of. I am looking for an efficient way to recursively nest these objects so that each chi ...

Extract information from JSON using a filter

Is there a way to extract the data value from the list without relying on index positions, considering that the order of arrays can change? I need to specifically target data where code === "size". Unfortunately, the existing structure cannot be ...