Friday, September 5, 2008

Writing HTML to the document

<script language="JavaScript">
<!--
document.writeln("Hello, welcome to my page.");
//-->
</script>


Insert the above into your html document between the <body> and </body> tags. The piece of text (known as a string) between the parentheses is the parameter given to the writeln() method. The browser will
display the HTML between the parentheses when it runs the script.

Note that writeln() writes actual HTML to the page, complete with tags, attributes and text. The
parameter of the writeln() method can include tags to format the text. Change the above code to the
following:

<script language="JavaScript">
<!--
document.writeln("<p><h1><center>Hello,welcome to my page.</center></h1>");
//-->
</script>


Note how the welcome message displayed by the browser is now a heading, and is centered.

The above example may seem kind of pointless, because we could have just inserted the HTML between the parentheses directly without using a script. This, however, makes it possible to create HTML that would vary depending on certain conditions. Insert the following code into your page:

<script language="JavaScript">
<!--
document.writeln("<p><br>This page is located at " +document.location+ " <br>This page was last modified on " +document.lastModified);
//-->
</script>


The HTML processed by the browser in this case would vary depending on the values of document.lastModified and document.location.

Because we wanted this text to be printed in the same position in our page body every time the page is loaded, we placed the JavaScript code between the <body> and </body> tags wherever we want the text to occur. Sometimes, we place JavaScript code in the head portion of the page if we want it to run before any of HTML in the body is displayed. We can also define JavaScript functions in the head of a page, which we will talk about later.

JavaScript has several predefined methods that allow you to create several types of pop-up boxes. Let's look first at "alert" boxes.