Write your first JavaScript - Learn through examples
JavaScript can be used in two different ways - (1) In the same HTML document, or (2) as a separate JavaScript file which can be linked by many HTML document. You'll use the first way if your script is specific only for one HTML document. But if your same script is used in many HTML documents then the second way of use is best.
JavaScript are included in a <script> tag. The beginning and end of a <script> tag can be written as follows:
<script language="JavaScript" type="text/javascript"> . . . </script>All your JavaScript then goes inside the above element. Let's start with this basic example.
now = new Date(); localtime = now.toString(); utctime = now.toGMTString(); document.write("<b>Local time:</b> " + localtime + "<BR>"); document.write("<b>UTC time:</b> " + utctime);The first line of the script creates a new variable now and create a new Date object. Note that every line of code in JavaScript ends with a semicolon ';' so do not forget that. The next two line create two new variable localtime and utctime, and the last two lines is a way to display the variable into the HTML document. The document.write(); function is used to create text or display the variable in the html document.
For this script to work, you'll have to put it inside an HTML document. Just create a simple HTML document and place the above codes in any part of the <body> section. Your complete HTML document would look like this:
<html> <head> <title>My JavaScript</title> </head> <body> <h1>Date and Time</h1> <p> <script language="JavaScript" type="text/javascript"> now = new Date(); localtime = now.toString(); utctime = now.toGMTString(); document.write("<b>Local time:</b> " + localtime + "<br />"); document.write("<b>UTC time:</b> " + utctime); </script> </p> </body> </html>Save the file and open it in your browser to see the effect. We'll talk more about the document.write(); function. This function take any string or variables and display that in the browser. You can just add any string by entering some text inside the parentheses and enclosed with quotations. Example document.write("Hello World!"); - this will display the word Hello World! in your browser. In the above example, you see a + sign. This operator is used to join the string "<b>Local time:</b> " with the variable localtime and again with the string "<BR>".
In the next tutorial, we'll show you more about variables and functions in JavaScript.
COMMENTS