With JavaScript you have several ways of writing text on websites. The simplest way, which is also a very stable solution, is the command document.write(). document.write() also has the advantage that you can easily write HTML code that be read and used along with the JavaScript. Also it is easy to merge text and variables and do various types of formatting.
Let's start with a simple piece of text. Text is written in quotes. As code it looks like this:
<SCRIPT TYPE="text/javascript">
document.write("Text with JavaScript");
</SCRIPT>
and on the screen, it will look like this:
HTML code is written like you would normally write you code, e.g. italics:
<SCRIPT TYPE="text/javascript">
document.write("Text with <I>JavaScript</I>");
</SCRIPT>
on the screen, it will look like this:
Because quotes works as start and stop for text, you can't just put parts of you test in quotes, without the execution of the JavaScriptet going wrong. The way to get around this limitation is to ad a backslash in front of the quote to be used in the text, i.e. this way: \". So, if we make a JavaScript that looks like this:
<SCRIPT TYPE="text/javascript">
document.write("Text with \"JavaScript\"");
</SCRIPT>
then it will look like this on the screen:
A piece of advice!
If you are going to make some of the more complex construction using document.write(), e.g. a table, it is advisable to split the code up in several lines of programming. Even if it isn't strictly necessary. It makes the code easier to handle and reduces the number of errors.
The code for a table, constructed using document.write(), consisting of one row with two cells, will look like this:
<SCRIPT TYPE="text/javascript">
document.write("<TABLE>");
document.write("<TR> <TD> </TD> <TD> </TD> </TR>");
document.write("</TABLE>");
</SCRIPT>
If you have text and variables that needs to be combined, this is done using a +. If you have a routine calculating today's date, and want to write it after the text "Today's date is", then the code looks like this:
<SCRIPT TYPE="text/javascript">
var TodaysDate = new Date();
var dd = TodaysDate.getDate();
var mm = TodaysDate.getMonth()+1;
var yyyy = TodaysDate.getFullYear();
TodaysDate = mm + "/" + dd + "/" + yyyy;
document.write("Today's date is " + TodaysDate);
</SCRIPT>
and on the screen it will look like this:
If you need more text or variables for the text you want to compose, you just keep on adding items using plus.