Ask Ben: Rendering Javascript Line Breaks

Posted July 17, 2008 at 7:27 PM

Tags: Javascript / DHTML, Ask Ben

Hi, I am learning Javascript and going through a self paced book. I am trying to use \n for new line in an example program, but it does not work. Here is the snippet:

//Display the current date and time on the web page
document.writeln(todays_date);

if (navigator.appName == "Microsoft Internet Explorer") {
document.write("\nYou are running Microsoft IE")
}else {
if (navigator.appName == "Netscape") {
document.writeln("You are running Netscape")
}
else {
document.writeln("You're not running Microsoft IE or Firefox")
}
}

As you can see I put "\n" before "You are running Microsoft IE", but it does not show the line in an new line. Why is that? Is it because I am using the write method? How do I make this line to show on a new line then? Thanks for your help.

The line break is actually working. The problem you are having is that it is not working in any useful way. If you could look at the "rendered" source of the page, you would notice that there is a line break. However, because a web browser does not inherently render line breaks, the displayed web page does not show you that the line is breaking. You can however, ask the browser to render the code exactly as-is by using something like the PRE tag. Take a look at this example:

 Launch code in new window » Download code as text file »

  • <!--- Render in standard way. --->
  • <script type="text/javascript">
  • document.write( "-Line one \n-Line two" );
  • </script>
  •  
  • <!--- Renader inside of PRE tags (renders as-is). --->
  • <pre>
  • <script type="text/javascript">
  • document.write( "-Line one \n-Line two" );
  • </script>
  • </pre>

Notice that we have the exact same code in the Javascript, but the second snippet executes within an HTML PRE tag. Running the above code, we get the following output:

-Line one -Line two
-Line one
-Line two

As you can see, the line break in the second output gets rendered while the first one does not.

Now, generally, you don't want to use PRE tags unless you are outputting something like code or CSV files. To get a line break in HTML, you would output the break tag "<br />" instead.

This doesn't mean that the \n character is useless - far from it. The \n does render line breaks in Textareas and any kind of Javascript alert:

 Launch code in new window » Download code as text file »

  • alert( "-Line one \n-Line two" );

It is also a valid character and can be used inside of Javascript variables. For example, you could take the text of a paragraph and split() it based on the "\n" character to get an array of the individual lines. But in general, you never render the \n character outside of form fields and Javascript alerts.

Download Code Snippet ZIP File

Post Comment  |  Ask Ben  |  Print Page



Learning ColdFusion 9 - ColdFusion 9 tutorials, samples, examples, demos

Reader Comments

Jul 17, 2008 at 8:13 PM // reply »
1 Comments

Or this should work as well

document.write("<br/>You are running Microsoft IE")


Jul 18, 2008 at 6:28 AM // reply »
111 Comments

To expand on Don's point a bit, think of it this way:

1. '\n' is the newline character for JavaScript output, so if you do alert("Error:\nThis is an alert");, then that message will popup on two lines.

2. '<br/>' is the newline character for HTML output, and HTML thinks '\n' is simply two characters to be displayed 'as is'.

HTH


Jul 18, 2008 at 8:05 AM // reply »
7,572 Comments

@JFish,

Well put.


Jul 21, 2008 at 12:41 PM // reply »
1 Comments

i´ve a problem in combination with perl. With /n there comes no linebreak


Jul 21, 2008 at 9:54 PM // reply »
1 Comments

So does CSS white-space:pre-wrap help Javascript \n to render in naked html:

<div style="white-space:pre-wrap;">
<script type="application/javascript">
if (navigator.appName == "Microsoft Internet Explorer") {
document.write("You are running\nMicrosoft IE")
}else {
if (navigator.appName == "Netscape") {
document.writeln("You are running\nNetscape")
} else {
document.writeln("You're not running\nMicrosoft IE or Firefox")
}
}
</script>
</div>


Jul 22, 2008 at 8:41 AM // reply »
7,572 Comments

@Peter,

To be honest, I have never tried that. I would stick with the use of the BR tag to create breaks. I think it is the more "intentful" way to create line breaks in HTML.


Jul 23, 2008 at 5:04 PM // reply »
1 Comments

@Peter

Yes, that should work if the browser is capable of using CSS. That said, it's not the ideal solution.

@no one in particular

\n is a literal return, like pressing the enter key while writing code, it will render a single space in the browser. Paragraph (p) and break (br) tags are preferred to messing with CSS properties. Also note that the return char for Windows is actually 2 chars (think it's line feed and return to home) and in Linux/Unix/BSD/Mac OS it is only one char (just the return, if I remember correctly).


Post Comment  |  Ask Ben

Recent Blog Comments
Mar 22, 2010 at 10:20 AM
POIUtility.cfc Examples For Reading And Writing Excel Files In ColdFusion
Can you please show me how to write to multiple sheets of a workbook? Thanks for your cool cfc. Khoa. ... read »
Lee
Mar 22, 2010 at 10:08 AM
Javascript's Implicit Boolean Conversions
I would certainly still use if(strValue.length > 0) over if(strValue) simply because I believe it makes the code more self-documenting. Not everyone knows that an empty string evaluates to false. ... read »
Mar 22, 2010 at 7:43 AM
Terms Of Service / Privacy Policy Document Generator
Thankyou for this very helpful form. You've made my life much easier today. I'll have a look around your site... I'm sure there's some more good stuff here..Thanks Dave ... read »
Mar 22, 2010 at 7:21 AM
Encountered "(. Incorrect Select Statement, Expecting a 'FROM', But Encountered '(' Instead, A Select Statement Should Have a 'FROM' Construct.
I got this exception now. In case you're using var-es local struct, CF gives you couple of "new" exceptions: Encountered "local. and Encountered "id. Incorrect Select List, Incorrect select colum ... read »
Mar 22, 2010 at 3:08 AM
Ask Ben: Selecting XML Attributes Given Other XML Attributes
Thanks for the response. I finally discovered that I was getting this error because I had cfsetting enablecfoutputonly="yes" in Application.cfc, and was neither setting it to false elsewhere nor brac ... read »
Mar 21, 2010 at 8:57 PM
The Bourne Ultimatum Starring Matt Damon And Julia Stiles
late to the party, but my observation is this: rewatch carefully for the platonic nature of the relationship between nicki and jason. she never flirts with him. he never comes on to her. they alway ... read »
Mar 21, 2010 at 7:40 PM
Is Simulating User-Input Events With jQuery Ever A Good Idea?
A couple of things. One you embed the initial state of of more-info in the CSS. IMHO, that behavior should be in jQuery: moreInfo.hide(); It shows that the behavior your toggling and closing is mor ... read »
Mar 21, 2010 at 3:59 PM
Exploring ColdFusion Component Runtime Class Properties And Serialization
@Elliott, according to Ben's experiment, serializeJSON() doesn't access the private data by default - it doesn't even access the getHair() method - so trying to clone a Girl.cfc via serializeJSON/des ... read »