nilay neeranjun
nilay neeranjun

Reputation: 145

How to add a new line to HTML text using JavaScript?

I am using this code which essentially types text onto the screen. I am unsure how to add a new line to the string which is being displayed.

I have already tried \n for those posting their answers. This does NOT work. A new line is not started in my HTML

Code:

var myString = "public class MyResume implements Resume{" +
    /*this is where I want the new line*/ "...." ;

var myArray = myString.split("");
var loopTimer;
function frameLooper() {
  if(myArray.length > 0) {
    document.getElementById("myTypingText").innerHTML += myArray.shift();
  } else {
    clearTimeout(loopTimer); 
    return false;
  }
  loopTimer = setTimeout('frameLooper()',70);
}
frameLooper();
<div id="myTypingText"></div>

Upvotes: 1

Views: 3818

Answers (5)

dangsonbk
dangsonbk

Reputation: 103

Why don't you just append ul>li or p to your text, something like this:

document.getElementById("myTypingText").innerHTML += "<p>" + myArray.shift() "</p>";

or

document.getElementById("myTypingText").innerHTML += "<li>" + myArray.shift() "</li>";

with:

<ul id="myTypingText"></ul>

Upvotes: 0

Gordon Merryweather
Gordon Merryweather

Reputation: 36

Here's an overly simplistic approach with full code. Use a tilde ~ and then watch for it in your frameLooper to insert a
like this:

<html>
<body>
<div id="myTypingText"></div>
<script>
var myString = 'public class MyResume implements Resume{~....' ;

var myArray = myString.split("");
var loopTimer;
function frameLooper() {
if(myArray.length > 0) {
    var char = myArray.shift();
        if (char === '~')
    { document.getElementById("myTypingText").innerHTML += '<br/>'; }
    else
    { document.getElementById("myTypingText").innerHTML += char; }
} else {
    clearTimeout(loopTimer); 
            return false;
}
loopTimer = setTimeout('frameLooper()',70);
}
frameLooper();
</script>
</body>
</html>

Upvotes: 2

Polyov
Polyov

Reputation: 2311

Simply adding <br> to myString doesn't work because you're inserting each character at one time. When a character gets added with innerHTML, JavaScript encodes it:

$('element').innerHTML += "<";
> "string&lt;" 

If you did this for each character in <br>, you'd end up with

>"string&lt;br&lt;"

You need some way to tell your script to add the entire element when you reach a "break character". You could use an uncommon character like a pipe | or you could add a method which looks ahead to make sure that the next few characters don't spell out <br>.

Upvotes: 2

Sharen.Z
Sharen.Z

Reputation: 41

You can also use <br>.Just like"your string.<br> new line"

Upvotes: 4

davidhu
davidhu

Reputation: 10432

To add string to a new line, you need the \n in your string. For example:

var string = 'This is the first line \nThis is the second line'

console.log(string)

This would output

This is the first line 
This is the second line

Upvotes: 1

Related Questions