Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.



Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this


  1. 1. Tutorial:Programming Understanding JavaScript JavaScript is not related to Java; JavaScript and JScript are both implementations of a notional standard language called ECMAScript. We explain the origin of these related languages and show how they can be used to enhance Web pages. Concluding our two-part article. By Mike Lewis O ne of the nice things about de- veloping in JavaScript is that you don’t need to buy any special tools: you already have every- earlier. You can also specify ”JScript” as the language, in which case it will be ignored by all versions of Navigator and Opera. displaying the text which appears be- tween them. However, the JavaScript interpreter correctly treats the en- closed text as code and executes it as thing you need to get started. You can In most cases, however, it is better normal. (The double forward slash is write the code using a simple text edi- not to specify a version unless you not officially part of the end-of-com- tor, and you use your normal Web know for sure which browsers will be ment tag, but is required in this context browser to test it. You could also write used. If necessary, your code can de- by Netscape Navigator.) the code using any Web authoring tool tect the browser version and act ac- If you want to include a comment which lets you directly edit the HTML; cordingly. within JavaScript itself, you have two the authoring tool does not need to be If the browser supports no scripting choices. If the comment occupies a sin- specifically JavaScript-enabled. language at all, it will simply disregard gle line, start it with //. To write a You write JavaScript code inside a the <script> tag. Unfortunately, this multi-line comment, start the com- normal HTML page. To separate the means that whatever appears between ment with /* and end it with */. Figure code from the rest of the page, you <script> and </script> will be treated 2 includes examples of both these delimit it with <script> and </script> as normal HTML text. The actual code styles. tags. Everything inside those tags is - such as the document.write state- You might want your HTML docu- interpreted as script, everything out- ment in the above example - will there- ment to take some special action if the side as HTML. The script tag includes fore be displayed as part of the browser does not support JavaScript, a Language attribute which identifies document, which is not what you or if the user has chosen to disable it. the specific scripting language: JavaS- want. For example, you might show a mes- cript in this case. You can prevent this by delimiting sage which warns that the page will The following code displays a sim- the script with the following tags: <!— not be displayed properly. You can do ple message in the Web browser: and //—> (see Figure 2, where a more this by means of the <noscript> and complete version of the Hello World </noscript> tags. Any HTML appear- <script language=”JavaScript”> example uses these conventions). ing between these tags will be dis- document.write(“Hello World”) HTML treats these tags as comment played if, and only if, scripting is not </script> delimiters and therefore refrains from currently available. For example: When the browser loads the page it Browser Supports will work through the contents in se- Navigator 2.0 JavaScript 1.0 quence, from top to bottom, executing Navigator 3.0 JavaScript 1.1 the script when it encounters it. Navigator 4.0 JavaScript 1.2 If you want to restrict the code to a Navigator 4.06 and above JavaScript 1.3 specific version of JavaScript, add the IE 3 JavaScript 1.0, JScript 3.0 version number to the language name. IE 4 JavaScript 1.1, JScript 3.1 IE 5 JavaScript 1.2, JScript 5.0 For example, if you specify the lan- Opera 3.21 and above JavaScript 1.1 guage as “JavaScript1.1”, the code will be ignored by Navigator 2.0 and ear- lier and by Internet Explorer 3.0 and Figure 1 - Browsers which support JavaScript. Update 140 (July 2000) Page 17 PC Support Advisor File: T0526.3
  2. 2. Tutorial:Programming <noscript> pear between the <script> and on the fly. For example, A=1 creates </script> tags. To reference the JS file a numeric variable; A=”Hello” This page requires JavaScript. from within your HTML document, changes the same variable to a use the SRC attribute in the <script> string. </noscript> tag. For example, if your JavaScript q Data types: the following types are code is in a file called HELLO.JS, you supported: number (integer and JS Files would reference it as follows: floating-point), boolean (true, false) and string (delimited with either Some JavaScript programmers pre- <script language=”JavaScript” single- or double-quotes). fer to keep their code separate from the SRC=”hello.js”> q Special values: the value null is an rest of the document. This makes it </script> “empty” value which is not equal to easier to read the script without being any other value that the variable distracted by HTML tags, and it can The filename in the SRC attribute can hold. The value undefined is also help with re-using the code in can include a directory path or a URL. similar, but it evaluates to the de- other documents. The code in the JS file is executed fault value for the appropriate data To achieve this, write your JavaS- instead of - not in addition to - any code type. cript in a separate text file, and save it between the <script> and </script> q Operators: JavaScript supports with the extension JS. The file should tags. If there is any non-script HTML around three dozen operators, in- contain JavaScript code only - that is, in the JS file, an error is generated. cluding many that will be familiar the text which would otherwise ap- to C programmers, such as ++ (in- Language Fundamentals crements a value by one) and += (performs addition and assigns the <html> JavaScript is not so very different result). <head> from C, Pascal, Basic, XBase and many <title>First Example</title> similar procedural languages. Any Data Conversion </head> programmer who already knows one JavaScript performs automatic con- <body> of these languages will have no trouble version between its various data types, <script language=”JavaScript”> understanding JavaScript’s funda- often in interesting ways. For example, <!— mental language elements. For the a boolean variable contains one of two document.write(“Hello World”) next part of the article, I will give you values: true or false. But it can legally // This is a 1-line comment an overview of these elements, starting be used in numeric expressions, in document.write(“<br>”) with some key points: which case true is considered to be /* You can include HTML equal to 1 and false to 0. In the follow- tags in the output. The q White space: JavaScript is a free- ing expression, a tax amount would be above inserts a line flowing language, in that the code added to the total if the boolean vari- break */ can include arbitrary spaces, tabs able Taxable was true, but not if it was and line feeds to improve readabil- false: document.write(“Greetings”) ity. There is no end-of-line delim- iter. Total = (Qty * Price) + (Taxable * // —> </script> q Case-sensitivity: you must be care- TaxAmount) </body> </html> ful to observe the correct case when referring to variables, functions, ob- Similarly, if a string happens to con- jects etc. For the most part, JavaS- tain a number, it too can be used in Figure 2 - Hello World cript is case-sensitive. arithmetic expressions. Thus, the fol- example, with comments. q Variable names: these may contain lowing code is valid: letters, digits and underscores, and must not start with a digit. (They Tax = “17” currDate = new Date() can also contain dollar signs, but Gross = 100 + Tax TimeNow = currDate.getHours() the ECMA standard recommends Withhold = true * Tax that these be reserved for use by if (TimeNow < 12) Strings { Greeting = “Good Morning” } automatic code generators.) else if (TimeNow < 18) q Declarations: you do not have to JavaScript strings can contain C- Greeting = “Good Afternoon” declare variables in advance, nor do like escape characters, including t for else Greeting = “Good you need to explicitly specify their tab, n or r for line feed or carriage- Evening” data types. A variable is created on return (these two have the same effect) the fly the first time that a value is and for backslash. But care is document.write(Greeting) assigned to it, and its data type is needed; HTML normally disregards determined from the value. What’s tabs and line feeds, so to use these Figure 3 - An if/else construct. more, the variable can be re-typed characters in displayed text you must File: T0526.4 PC Support Advisor Update 140 (July 2000) Page 18
  3. 3. Tutorial:Programming JavaScript format the text with the HTML <PRE> Arrays are always zero-based - that in your code. Optionally, functions can style. is, the first element’s subscript is 0. receive parameters and return a result. Strings can also contain HTML for- Array elements can contain any data The result can be used just like any matting tags. As an example, the fol- type, not necessarily the same type for other value, for instance in an expres- lowing code displays three names, all elements. An element can even con- sion. each on a separate line, with the mid- tain another array: For example, here is a function dle one in bold: which returns the mean average of the MyArray = new Array(20) two numbers which are passed to it as document.write(“Tomn<B>Dick<B>- MyArray[5] = new Array(10) parameters: nHarry”) MyArray[5][0] = “Hi” function MeanAv(n1,n2) Arrays You are not obliged to specify the { return (n1+n2)/2 } Unlike simple variables, arrays length of the array when you create it, must be explicitly declared before they and your code can change the length Note the use of braces to enclose the can be referenced. You declare an ar- dynamically. In this example, the array body of the function. These are man- ray with the operator new, like this: will initially be of length zero: datory, even if the function contains only one statement. MyArray = new Array(20) Arr1 = new Array() JavaScript programmers usually place their function definitions in the This creates an array called MyAr- To increase the length, simply as- document’s head - that is, between the ray with 20 elements. The elements sign a value to an element beyond the <HEAD> and </HEAD> tags. This is start life with no specific data type, and end of the array: not obligatory, but it does ensure that their initial value is the special value, the function is defined before it is undefined. To reference the elements, Arr1[9] = “Greetings” called. This is especially important use square brackets: where event-handlers are used (more Program-Flow Constructs of this later). Figure 5 shows an exam- MyArray[3] = “Hello” JavaScript supports a range of ple. This performs the same action as branching and looping constructs, the code in Figure 4, but it uses a sepa- for (i=1;i<7;i++){ similar to those found in other lan- rate function to perform the actual out- tag1 = “<H“+i+”>” guages. You can use if/else or a switch put. tag2 = “</H“+i+”>” statement to test conditions. Three Document.write(tag1+“Heading constructs are available for executing a Object Orientation level ”+i+tag2)} block of code repeatedly: for, while, and do/while. The syntax of these con- The language elements I have de- Figure 4 - A for loop. structs closely resembles that of C. scribed so far can be used to produce Figure 3 shows a simple if/else con- worthwhile JavaScript programs struct. Note that I have used braces to which can greatly enhance your Web enclose the block of statements follow- pages. However, the real power of <html> ing the first test. These braces are in JavaScript only becomes apparent <head> fact optional if the block contains just when you make use of two further <title>Function call one statement, as is the case here. Note concepts: objects and events. example</title> also that, unlike in C, there is no semi- JavaScript is not a pure object-ori- <script language=”JavaScript”> colon at the end of the construct (al- ented language. It does not let you <!— though no harm is done if this is create new classes through inheri- function ShowHeading(str,lev) included). tance, nor does it support the concept {document.write(“<H“+lev+”>- “+str+”</H“+lev+”>”)} For an example of a for loop, look at of a class hierarchy. However, it does // —> </script> Figure 4. Here we are executing a allow you to create new instances of </head> document.write statement six times. objects and to access their properties Each time round the loop, we generate and methods. More importantly, the <body> a message consisting of the name of the browser environment supplies a range <script language="JavaScript"> next consecutive HTML heading style of pre-defined objects which let you <!— for (i=1;i<7;i++) (using the <Hn> and </Hn> tags). In interact with Web pages in many use- ShowHeading(“Heading level ”- each case, the message is formatted in ful ways. +i,i) the style in question. We have already used one of these // —> </script> built-in browser objects: the docu- </body> Functions ment. The document object embodies </html> the properties and methods of the As you would expect, JavaScript lets you define functions, which you document currently loaded in the Figure 5 - A function call. can subsequently call from elsewhere browser window. When you issue a Update 140 (July 2000) Page 19 PC Support Advisor File: T0526.5
  4. 4. Tutorial:Programming document.write statement, you are in an array can itself hold objects. For cally performed by the user. For exam- fact calling the write method of the example, the document object has a ple, when the user clicks on a button, document object. property called links. This is an array, the button-click event occurs; when a Other pre-defined browser objects which in turn holds a set of objects, document is loaded in a window, the include window, history and naviga- each of which is of type link. Each link window-load event occurs; and so tor. The various elements that can ap- object is a reference to an instance of a forth. pear in forms (text boxes, radio hyperlink within the document. (Care By writing “event handlers” you buttons, submit buttons etc) are also is needed here: links, in the plural, is can make your documents respond to objects. For details of these and other the array; link, in the singular, is an these events. Thus, if you wanted to browser objects, see Figure 6. individual object within the array.) prompt the user for confirmation be- JavaScript also lets you define en- The following code iterates the fore following a link, you could write tirely new object types and to create links array and displays the URL asso- an event handler for the link’s click instances of objects based on them. ciated with each link contained in it: event. The event handler would con- There are also several built-in object tain the code which prompts for con- types (built-in object types are not the for (i=0;i<document.links.- firmation. The code would be executed same as built-in objects). For an exam- length;i++) whenever the user clicked on the link. ple, look back at Figure 3. The first line document.write(document.links- The syntax for event-handlers is in this code creates an object called [i].href) somewhat different from the code that currDate, which is based on the built- we have seen so far. Each event is as- in Date object type. In the first line of this example, we sociated with an HTML element. Although it might not be obvious, use the length property of the links When you write JavaScript code to re- JavaScript arrays are also objects. array (remember, an array is also an spond to an event, you do not place it When you declare an array, you are in object) to determine how many hyper- within the <script> and </script> tags. fact creating a new instance of an ob- links exist in the document. In the sec- Rather, you make it an attribute of the ject based on the built-in Array object ond line, we display each individual tag of the element to which it relates. type. link object’s href property, which con- For example, the following code tains the target URL. displays an alert when the user clicks Object Syntax on a link: The basic syntax for working with Events objects is sometimes called dot nota- <p><a href=“” tion. This simply means that, when To a large extent, JavaScript is an OnClick = “alert(‘You are leaving referring to a property or method, you event-driven environment. An event the page’)”> precede its name with that of the object occurs as a result of some action, typi- </a></p> that it belongs to, using a dot as a separator. Object Details For example, to change the current navigator The browser itself document’s background colour, you window The browser window or a frame within the window would assign a value to the document history The list of URLs recently accessed from the window object’s bgColor property, like this: document The currently-loaded HTML document frame An HTML frame document.bgColor = “Blue” link A hypertext link image An image in an HTML document location A URL Similarly, to display a message box, form An HTML form you would call the window object’s button A button in a form alert method: checkbox A checkbox in a form hidden A hidden field in a form window.alert(“Time for lunch”) password A password field in a form radio A set of radio buttons in a form reset A reset button in a form The window object is different from select An option list (listbox or combo box) in a form the others in that it is assumed to pre- option An item within an option list sent if no object is specified. In other submit A submit button in a form words, if you omitted the word win- text A one-line text field in a form textarea A scrolling text field within a form dow and the subsequent dot in the screen The screen display above statement, it would work in just embed An embedded object in a document the same way. applet A Java applet embedded in an HTML document Most properties are simple values, mimeType A mime type supported by the browser such as the bgColor property shown plugin A plug-in supported by the browser above. However, it is also possible for a property to be an array. What’s more, Figure 6 - Browser objects. File: T0526.6 PC Support Advisor Update 140 (July 2000) Page 20
  5. 5. Tutorial:Programming JavaScript The event we are responding to order form for an online shopping site. As an example, consider a Java ap- here is the click event associated with Let’s suppose that the order is subject plet which displays various types of the link. The code which is to be exe- to a minimum quantity of 100 units. If charts. Let’s suppose that the applet cuted when this event happens is the user enters a value below that fig- has a class called Charts; this in turn stored in the string to the right of the ure, we want to display an alert and has a method called BarChart(). To ac- equals sign in the second line. This reject the value. cess the applet from your JavaScript string is assigned to the OnClick attrib- A good place to do this check would code, you first incorporate it into the ute of the link. (The relevant attribute be in the blur event of the order quan- page using the standard HTML applet names are always the same as the cor- tity field. As its name might suggest, tag: responding event names but preceded this event occurs when the field loses by On.) focus. <applet code=“Charts.class” Note that, although the string con- Figure 7 shows how the code might name=“mychart” tains JavaScript code, the entire con- look (for clarity, I have excluded de- width=100 height=50> </applet> struct is HTML, not JavaScript. For tails which are not relevant to the ex- that reason, the event attribute name ample). As you can see, a separate Once this has been done, JavaScript (OnClick in this case) is not case-sensi- function, called ValidateQty(), per- can access the applet’s variables and tive. forms the validation and displays the methods through the browser’s built- In the above example, we are exe- alert. If the check fails, this function in applet object. This object, which is a cuting a single JavaScript statement in also calls the field’s focus() and select() property of the document object, lets response to the event. It is possible to methods to ensure that focus remains you reference specific applets by place multiple statements in the string, in the field. If it did not do this, the user means of their class names. So the code using a semi-colon as a separator. could simply ignore the error. to call the Chart applet’s BarChart() However, in these cases it is usually Note that the validation function method would look like this: more convenient to place the code in a treats a value of zero as being valid. function, and to call the function from This allows the user to skip the order document.Chart.BarChart() the event attribute. We’ll see an exam- quantity and return to it later. To pre- ple of this in a moment. vent a zero order quantity from being For this to work, the applet’s class sent to the server, the field should be name, and the names of the relevant Form Validation re-checked when the user submits the variables and methods, must be de- form (that is, in the form’s submit clared public. This is simply a matter For a more complete example of event). For that matter, all checks of of adding the keyword public to the event processing, we will return to the this type should also be repeated by appropriate declarations in the Java scenario I mentioned at the start of the the server just in case the user does not code. article: validating the contents of an have JavaScript enabled. ActiveX controls are slightly more difficult to handle. Essentially, you use Component Scripting the <object> tag to insert the control <html> <head> into the document and to specify the <script language=“JavaScript”> Although JavaScript and Java are values of its various attributes. These <!— quite separate, they can interact with include the control’s CLSID (a unique function ValidateQty(fld) each other in several useful ways. Spe- code that identifies every COM com- { if (fld.value !=0 && cifically, you can use JavaScript to pro- ponent) and the initial values of its fld.value < 100) grammatically access the variables properties. The control’s events are de- { alert(“Minimum order is (properties) and methods of a Java ap- clared by means of additional attrib- 100 units”) fld.focus() plet, and you can similarly use Java to utes to the <script> tag. } interface with JavaScript objects. It is In practice, you can avoid much of } also possible for JavaScript to interact the coding associated with ActiveX // —> </script> with ActiveX controls. controls by using a suitable HTML </head> These features can do a great deal authoring tool. In FrontPage 2000, for to enhance the functionality and ap- instance, you can insert the control via <body> <p><input type“=TEXT” pearance of your JavaScript applica- the Insert menu, and adjust its proper- name=“Qty” size=“20” tions. Java applets and ActiveX ties from a dialog which you reach by OnBlur = “Vali- controls can take you well beyond right-clicking on the control in the ed- dateQty(Qty)”></p> what JavaScript on its own can iting window. These actions will auto- </form> achieve. For example, there are applets matically generate the <object> tag </body> and controls which can supply sophis- and its various attributes. </html> ticated user interface elements, such as pop-up calendars, expandable trees, progress bars and Windows Explorer- Server-Side Scripts Figure 7 - Form validation example. style views. So far, this article has concentrated Update 140 (July 2000) Page 21 PC Support Advisor File: T0526.7
  6. 6. Tutorial:Programming on client-side JavaScript. The main dif- ference in server-side scripting is that the scripts are compiled in advance, “In a Netscape environment, the script and left to execute in the background, waiting for a request from a client. The requires a FastTrack or Enterprise language and syntax are almost the same, but server-side scripts have ac- server, and is supported by a Netscape cess to a different range of built-in ob- jects. There are also some differences technology called LiveWire.” in the associated HTML tags. When writing server-side JavaS- cript, you need to know what type of server it will run on. In a Netscape and returns HTML pages to the Conclusion environment, the script requires a browser. ASP is not specific to JavaS- FastTrack or Enterprise server, and is cript; it also supports VBScript and This article has presented a brief supported by a Netscape technology Perl. introduction to what is undoubtedly a called LiveWire. Among other things, Like LiveWire, ASP provides ob- very substantial and capable lan- LiveWire provides a JavaScript com- jects for performing low-level file ac- guage. I have described the basic con- piler which converts the script to a cess on the server and for accessing cepts, but there are many details which bytecode file (with the extension back-end databases via ODBC. I do not have space to cover. WEB). Another LiveWire component, To finish, here is a simple example To learn JavaScript properly, you called Application Manager, is then of a server-side script. These three will want to find out more about the used to activate the compiled code. lines of LiveWire code display the built-in objects and the event model, The script actually runs when the user user’s IP address in the browser win- and you will probably want to delve opens its URL in the browser. dow: further into server-side scripting as LiveWire also provides a way for well. Fortunately, there are many JavaScript code to store permanent in- books and online resources available formation on the server. By using the <SERVER> to help you do that. My aim has been File object, the script can perform low- write(“Your IP address is ”+- to encourage you to get started with level input and output to serial files. request.ip) this very useful technology. Alternatively, you can use the data- </SERVER> base object to access back-end data- bases via ODBC. These tools make it Note the use of the <SERVER> and possible to write full-blown server- SERVER> tags in place of <SCRIPT> side applications which collect data and </SCRIPT>. The request object from the user, execute queries, gener- provides details of the requesting ate reports, and quite a lot more. browser. The ASP equivalent of this The Microsoft equivalent of code would not include the <SERV- LiveWire is Active Server Pages (ASP). ER> tags, but would instead have a This runs on Microsoft’s Internet Infor- Language declaration at the top of the mation Server (IIS) and Personal Web document. The syntax for using the PCSA Server. It provides a run-time engine Request object (note there is a capital which interprets server-side scripts R in the Microsoft version) would also (held in files with the extension ASP) be slightly different. JavaScript Resources If you are interested in going further with JavaScript, you can download Copyright ITP, 2000 a full set of Netscape reference manuals and tutorials from devel- For the complete JScript documenta- tion, go to and follow the download link. Both sites also have useful FAQs. The official ECMA 262 standard is available from Note The Author that this is a formal specification and is not intended as a learning aid. Mike Lewis is a freelance technical There are no significant third-party sites devoted exclusively to JavaS- journalist and a regular contribu- cript. However, Gamelan ( and Java World tor to PCSA. You can contact him ( are two Java-oriented sites which also provide use- by email at mike.lewis@itp-jour- ful JavaScript content. File: T0526.8 PC Support Advisor Update 140 (July 2000) Page 22
  7. 7. New Reviews from Tech Support Alert Anti-Trojan Software Reviews A detailed review of six of the best anti trojan software programs. Two products were impressive with a clear gap between these and other contenders in their ability to detect and remove dangerous modern trojans. Inkjet Printer Cartridge Suppliers Everyone gets inundated by hundreds of ads for inkjet printer cartridges, all claiming to be the cheapest or best. But which vendor do you believe? Our editors decided to put them to the test by anonymously buying printer cartridges and testing them in our office inkjet printers. Many suppliers disappointed but we came up with several web sites that offer good quality cheap inkjet cartridges with impressive customer service. Windows Backup Software In this review we looked at 18 different backup software products for home or SOHO use. In the end we could only recommend six though only two were good enough to get our “Editor’s Choice” award The 46 Best Freeware Programs There are many free utilities that perform as well or better than expensive commercial products. Our Editor Ian Richards picks out his selection of the very best freeware programs and he comes up with some real gems. Tech Support Alert