My Profile

Sunday, January 23, 2011

Writing a Simple JavaScript Application


In this section, you explore the process of JavaScript development with a simple JavaScript application. This application doesn't do much, but it will help you understand the steps required to develop and test a script. You'll find much more sophisticated examples throughout this guide.

Creating the Script


First, let's look at a very simple JavaScript application. The following script simply displays the location of the current page and a brief message. This script will be combined with an HTML page and its use demonstrated. document.write("<B> location: </B>" + document.location + "<br>") document.write("This is a test of JavaScript." + "<br>")
After you've created the script, you need to do two things:
  1. Embed the script in the HTML page. You can use the <SCRIPT> tag to do this, or use an event handler.
  2. Test the script by viewing the document with Netscape.

Embedding the Script in an HTML Page


There are two ways to embed a JavaScript script in your HTML page. Each has its advantages and disadvantages. In a complex JavaScript application, you'll end up using both of these methods several times.

Using the <SCRIPT> tag


The simplest method of including a JavaScript script in an HTML page is to use the <SCRIPT> tag, as described earlier in this chapter. This tag is usually used as a container, and the script is included directly after it. Listing 1.3 adds the necessary opening and closing <SCRIPT> tags to the script:


Listing 1.3. A simple example of the <SCRIPT> tag.
<!-- <SCRIPT language=JAVASCRIPT> document.write("<B> location: </B>" + document.location + "<br>") document.write("This is a test of JavaScript." + "<br>") </SCRIPT> -->

Notice the strange syntax. The extra brackets and exclamation marks indicate a comment; the entire script is marked as a comment so that older browsers will not attempt to display it. JavaScript-aware browsers will execute it correctly.
If you use this method within the body of a Web page, the script will be executed immediately when the page loads, and the output of the script will be included at that point in the page. You can also use the <SCRIPT> tag within the header of a page to prevent it from executing immediately. This can be useful for subroutines that you will call later. 

---------------------------------------------------------

** If you like this post please like our page in facebook

0 comments:

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More