document.write('<strong> Welcome to JavaScript Tutorial</strong>')Save this file with an extension .js in a folder of your choice. We advise you to create a particular folder to store all your JavaScript files for this tutorial. You can access the file from a webpage by using the HTML <script></script> tag. Let's say you save the aforementioned file with the name welcom.js, you can access this file by linking it from a webpage as shown in Example 2.1.
<html> <head> <title>My first JavaScript</title> </head> <body> <script src="welcome.js"></script> </body> </html>
The output is a one-line sentence as follows:
<Script>
Statements
</Script>
<html> <title>My FirstJavaScript</title> </head><body> <script> document.write( "<b> Welcome to JavaScript Tutorial </b>" ); </script> </body> </html>
A JavaScript structure comprises a series of statements that enables a webpage to perform certain tasks, for example, to display the greeting message on your browser based on the local time, as shown in Example 2.3.
<script> CurDate=new Date(); timeNow=CurDate.getHours(); var greeting; if (timeNow>18) { greeting='Good Evening'; } else if(timeNow>12){ greeting='Good Afternoon'; } else if(timeNow>0) { greeting='Good Morning'; } else { greeting='Good Day'; } greeting=greeting.fontcolor("red"); greeting=greeting.bold(); greeting=greeting.fontsize("10"); greeting=greeting.italics(); document.write(greeting); </script>
The greeting message is as showns below:
The curly bracket { } indicates the start and end of a JavaScript code block. Each statement is separated by a semicolon. The JavaScript code usually includes objects and their associated methods. Let's explore the document object and its write() and writeln() methods.
document.write(HTML Expression)
Another method associated with the document object is the writeln() method. Write and writeln are basically the same, except that writeln appends a new line at the end of the text. Writeln has to be used together with the <PRE> or <TEXTAREA> tags. Let me illustrate the difference with the following example:
<html> <head> <title>Write and Writeln</title> <script> document.write( "<pre><b>Displaying text with the write method</b>" ); document.write( "<b> The following sentence appear on the same line </b></pre>" ); document.write("<hr>"); document.writeln( "<pre><b>Displaying text with the writeln method</b>" ); document.writeln( "<b>The following sentence appear on a new line </b></pre>" ); </script> </head><body></body> </html>
*Every statement in a JavaScript must end with a semicolon ;
Note: document.write("<hr>"); add a horizontal line across the web page
Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy