2

var i = 0;
var string = "Size: test ";
var speed = 50;

function printtext() {

  if (i < string.length) {
    document.getElementById("demo").innerHTML += string.charAt(i);
    i++;
    setTimeout(printtext, speed);
  }

}
<button onclick="printtext()">Click me</button>
<div id="demo"></div>

I am trying to seperate "Size:" and "test". I would like "test" to be on the next line (under) so that when my button is clicked, it displays (like a typewriter) a list of information.

Conclusion: I'm just trying to find a way to go to the next line like some sort of \n.

Thank you,

Nathan

FZs
  • 16,581
  • 13
  • 41
  • 50
Nathan
  • 113
  • 1
  • 2
  • 9
  • You don't have to add `(solved)` to the question title. Marking an answer is enough – FZs Apr 14 '20 at 09:01

3 Answers3

2

Since the only thing that separates Size: and test strings is a whitespace, you can simply check if string.charAt(i) is a whitespace character. If it is, then you simply print a <br /> tag instead of the whitespace character itself.

var i = 0;
var string = "Size: test "; 
var speed = 50;

function printtext() {

  if (i < string.length) {
    var character = string.charAt(i);
    if (character === ' ') {
      character = '<br />';
    }
    
    document.getElementById("demo").innerHTML += character;
    i++;
    setTimeout(printtext, speed);
  }

}

printtext();
<div id="demo"></div>
Terry
  • 63,248
  • 15
  • 96
  • 118
0

The easiest way is probably to use a <pre> element as the target, and \ns for linebreaks.

That way, you can even avoid the use of .innerHTML and use .textContent or .innerText instead (which one you like).

You could also apply some CSS to restore the default font:

var i = 0;
var string = "Size:\ntest ";
var speed = 50;

function printtext() {

  if (i < string.length) {
    document.getElementById("demo").innerText += string.charAt(i);
    i++;
    setTimeout(printtext, speed);
  }

}
pre{
  font: initial
}
<button onclick="printtext()">Click me</button>
<pre id="demo"></pre>
FZs
  • 16,581
  • 13
  • 41
  • 50
0

You can do that with little if statement, like you can say if string.charAt(i) === " ") put <br> to get next line

Code ↓↓

var i = 0;
var string = "Size: test ";
var speed = 50;

function printtext() {

  if (i < string.length) {
     if(string.charAt(i) === " "){
         document.getElementById("demo").innerHTML += "<br>";
     }
     else 
       document.getElementById("demo").innerHTML += string.charAt(i);
    i++;
    setTimeout(printtext, speed);
  }

}
<button onclick="printtext()">Click me</button>
<div id="demo"></div>
Hasan_Naser
  • 204
  • 3
  • 13