an introduction to javascript scripting programming

22
This eBook was designed and published by w3opensource.com. For more free eBooks visit our Web site at http://www.w3opensource.com/ . To hear about our latest releases w3opensource Newsletter To purchase the full licensed version - click on the button An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce Copyright © w3opensource.com All rights reserved

Upload: alexis-gklinos

Post on 13-May-2015

2.191 views

Category:

Education


4 download

DESCRIPTION

An introduction to JavaScript Scripting Programming

TRANSCRIPT

Page 1: An introduction to JavaScript Scripting Programming

This eBook was designed and published by w3opensource.com.

For more free eBooks visit our Web site at http://www.w3opensource.com/.

To hear about our latest releases w3opensource Newsletter

To purchase the full licensed version - click on the button

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 2: An introduction to JavaScript Scripting Programming

Teach

Yourself

in 6 hours

      An Introduction to

  JavaScript  

Scripting Programming

Introduction to Web Scripting Programming The JavaScript structure The element script and its attributes Embedding Scripts within HTML documents JavaScript Comments Organizing scripts & order of execution The incompatibility of Browsers Defining the Scripting language

by Alex Gklinos M.Sc. in E-Commerce

Client Side Web Technologies The most cost-effective valuable e-books at w3opensource.com

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 3: An introduction to JavaScript Scripting Programming

   

  An Introduction to  

 JavaScript Scripting Programming

Learning An Introduction to JavaScript Scripting Programming you will be able to understand how do you create and embed JavaScript scripts to your documents for more dynamic presentation.

You will know the structure of the language and how do you organize your scripts and the order of their execution.

Especially you will learn :

How to separate the Client and Server Side Scripting Programming How to use the elements of the language How to design a structured web document How to design an object oriented web document How to use the element script and its attributes How to hide the Scripts within comments How to embed Scripts within HTML documents How to organize scripts and their order of execution How to use objects through functions as their methods How to control the User's Browser compatibility How to define the scripting language of your scripts

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 4: An introduction to JavaScript Scripting Programming

Chapter 1 : Web Scripting Programming

1.1. Client - Side Scripting 1.2. Web Server -Side Scripting 1.3. JavaScript versions 1.4. Comparing JavaScript to Java Chapter 2 : The structure of JavaScript

2.1. The elements of the language 2.2. Structured Programming 2.3. Object Oriented Programming (OOP) 2.4. The element script and its attributes 2.4.1. The HTML element script 2.4.2. The attributes of the element script 2.4.3. Hiding the Scripts within comments

Chapter 3 : Embedding Scripts within HTML documents

3.1. Within the document body 3.2. In the first section of the page header 3.3. Within HTML tags by an event handler 3.4. Calling an external file through the <script> tag 3.5. JavaScript comments Chapter 4 : Organizing scripts & order of execution

4.1. User Interface 4.2. Using objects 4.3. Methods and functions 4.4. Events and Event Handlers 4.5. The incompatibility of Browsers 4.5.1. Plug-ins 4.5.2. Browser information 4.5.3. Table of features of most common browsers

Chapter 5 : Defining the Scripting language

5.1. The type of the Script Language 5.2. The Default Script Language 5.3. Alternate content & Noscript element 5.4. An External Script for the current Date and Time Summary Learn More

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 5: An introduction to JavaScript Scripting Programming

1. Web Scripting Programming

 

The inability of HTML to cover the needs of interactivity between an internet user and a web page of a site being visited, gave birth to Script programming languages.

With a Script programming language a web programmer or an author of an HTML document can incorporate script programs into the HTML code of his documents so that, when they are interpreted and parsed by the user's browser, a communication of the form question-response is possible. The new Economy of the e-Commerce has been based on this Client-Server model.

Scripting programming can be either a couple of commands or entire applications that the user's browser will execute, when the user downloads our site to his system or when the user's browser asks our web server to respond to certain actions.

In the first case we refer to Scripting programming done on behalf of the client on his own computer and is interpreted by his browser. In the second case we refer to Scripting programming done on behalf of the web server, the computer that accommodates our web documents or web applications which are executed there and their responses or results are sent to the client browser. In any case, Script programming languages are interpreted languages by the browsers. When a user's browser asks for an HTML document with embedded JavaScript code from a web server , the server sends the entire content of the document through the web. The document may contain both HTML statements as well as JavaScript statements. Once the user's browser downloads the document, it is parsed from top to bottom, interpreting every line and displaying HTML tags and JavaScript statements as they are encountered.

1.1. Client-Side Scripting

When we create an HTML document, intending to incorporate Script programs in it, we must have decided beforehand which Scripting Language we are going to use.

JavaScript

is today the international standard of a Scripting Language and can be used in web pages and the creation of interactive applications. It's great advantage is that it is supported by most of the common browsers on the market.

VBScipt

by Microsoft is an equally powerful Script Language, but is supported only by

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 6: An introduction to JavaScript Scripting Programming

Internet Explorer.

JSript

is a JavaScript version by Microsoft that covers almost every aspect of Netscape JavaScript which is why it is referred to as JavaScript too.

ECMAScript

is a Script Language set by the European Computer Manufacturers Association (ECMA) on ECMA-262 standard. ECMAScript was developed based on JavaScript and JScript with a view to becoming the international standard of the language syntax and formatting.

Every new version of a browser that includes JavaScript must comply with the ECMA-262 standard of ECMAScript. The ECMA-262 standard has been certified by the International Organization of Standards (ISO) as ISO-16262. The selection of the Script language is of ultmost importance since it must be supported by the browser (client-side). Given that 99% of the web users internationally use the most popular browsers, Internet Explorer and Netscape Navigator, JavaScript is the most secure and reliable choice. Therefore, the scripts that are executed on the client side when their browser downloads the web pages they choose on the internet must be written in a Script language their browser supports, otherwise they will either not see them at all or what they see will be overlapping text, distorted pictures or graphics and generally speaking ruined web pages.

1.2. Server-Side Scripting

When it comes to Web Server Scripting programming, the languages used may be different from the ones the user's browsers support. The reason is quite simple; the server Script programs are executed only on the server side and their results is what the user's browser displays on the screen. The most widely used Web Server Scripts or interface programs are CGI (Common Gateway Interface) Scripts, written in Script languages such as PERL, Visual Basic, C or C++. Also in interactive-web applications (Server-Client) , technologies are used such as :

ΑSP (Active Server Pages) of Microsoft,

JSP (Java Server Pages) of Netscape,

SSJS (Server Side JavaScript) of Netscape,

VBScript in the first case and Java or JavaScript in the second are the languages chosen for

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 7: An introduction to JavaScript Scripting Programming

programming on the Server Side.

Since ASP technology of Microsoft supports JavaScript, the scripts that are embedded in the pages executed on the client side, can be written in JavaScript and the scripts executed on the web server side can be written either in VBScript or JavaScript. The choice is yours.

As far as Netscape technologies are concerned, both Java(JSP) and JavaScript(SSJS), that can be chosen and used on the server side, you must know that in both cases the HTML pages along with Server-side JavaScript code they may contain are compiled into executable byte code. This means that the web server that accommodates and parses these pages must contain the JavaScript runtime engine. When the user's browser asks from the server a JSP or SSJS page, the server finds the relevant executable code page and reproduces it dynamically in HTML, which HTML page is finally returned to the client.

In contrast with CGI interface programs, the whole JavaScript code is, as already mentioned, dynamically reproduced in HTML pages , which makes it very easy to develop and maintain applications.

1.3. JavaScript versions

JavaScript is a  Web Scripting language developed by Netscape. Its original name was LiveScript and was first launched in 1995 along with Netscape Navigator 2.0.

JavaScript as an Interpreted Script programming language, intends to incorporate in HTML documents features such as :

graphics, sound, animation effects, video and interaction with the user in very many ways.

JavaScript versions are :

1. JavaScript 1.0 with NΝ 2.0 and ΙΕ 3.0 2. JavaScript 1.1 with NΝ 3.0 and ΙΕ 4.0 3. JavaScript 1.2 with NΝ 4.0 - 4.05 and partly by ΙΕ 4.0 4. JavaScript 1.3 with NΝ 4.06 - 4.5 and ΙΕ 5.0 (fully ECMA -262 compatible) 5. JavaScript 1.5 with NΝ 6.0 and ΙΕ 5.5, ΙΕ 6.0

As examples of JavaScript applications we can mention :

The validation of the contents of a form. The arithmetic calculations of Table fields, file records, variables etc. Moving or rolling messages. Animation effects with pictures or graphics. Detecting the installation of certain plug-ins on the user's browser. Detecting the user's browser and cross browsing to a different part of a page. Interactive banners. Interactive pictures or graphics.

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 8: An introduction to JavaScript Scripting Programming

 

Note: JavaScript 1.3, is fully compatible with ECMA - 262 standard. In this version the Unicode character set is supported. The most recent version ECMA -262-3, was published in December 1999 and is based on JavaScript 1.5 of Netscape.

1.4. Comparing JavaScript to Java

JavaScript

Is an interpreted language and not compiled. The JavaScript interpreter depends on the user's browser. It is Object-oriented. There is no distinction between the types of objects. Its objects follow the Inheritance through the prototype mechanism, and its properties and methods can be added to any object dynamically. Its Code is created inside and outside of the HTML document embedded very simple to it. There is no need to declare the data types for its Variables. It support dynamic typing declaration. It does not support a File Management System and thus it cannot automatically write to hard disk.

JavaScript is a very flexible and free-form language compared to Java. As you can see there is no need to declare all variables, classes, and methods. Also you do not have to worry whether methods are public, private, or protected. Additionally you do not have to declare variables and implement interfaces..

Java Is a compiled byte codes language and its compiled byte code downloaded from the web server in order to be executed on the client site It a full Class-based language.and its objects are divided into classes and instances. All objects follow the inheritance through the class hierarchy. Classes and instances cannot have properties or methods added dynamically. Java Applets as small APIs can be embedded into HTML pages and executed through them. You have to declare the types of data for which you are going to use them. It supports only static typing declaration. It does not support a File Management System to write automatically to hard disk.

Java is designed for fast execution and type safety. as a full class-based programming language. The class-model of Java demands programs consist exclusively of classes and their methods. Additionally Java's class inheritance and object hierarchies as well as variables typing declaration make Java more complex than JavaScript programming.

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 9: An introduction to JavaScript Scripting Programming

2. The structure of JavaScript

JavaScript statements are separated by a semicolon (;). These statements create variables, assign values to them, compare the contents of variables and generally create and execute, step by step, the code of the program.

As an integrated and object-oriented programming language - made by mathematicians- it is equipped with all the functions of a modern language, as:

Variables, Operators Expressions Statements, Objects Events Event handlers Methods and Functions

The previous elements, along with their grammar and syntax, form the language.

2.1. The elements of the language

Τhe elements, that make up JavaScript more analytically are :  

 

Variables  are certain memory locations whose content may change. JavaScript dynamically defines the variable type depending on the content assigned to it by the programmer.

Operators are used to calculate or compare values. Example: Two arithmetic values are added using the addition operator (+) sum=150+100 or compared using the "greater than" operator (>) sum>200

Expressions are combinations of variables, operators and statements.

Example: The two statements that follow are expressions: sum=150+100 ; if ( sum>2000)

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 10: An introduction to JavaScript Scripting Programming

Statements are code that can refer to variables, JavaScript objects.

These objects can be forms, frames, tables, buttons, links etc., and can appear on its own or within expressions. Example: if ( sum>2000) {statements ;} else {statements ;}

Objects are the whole philosophy of JavaScript .

JavaScript treats each part of an HTML document as an object with properties and a certain value for each property. The properties of an object act as independent variables, which means that their values can change. JavaScript treats an HTML document itself as an object and allows the programmer to divide it into more analytical objects - creating built-in objects, so that each one covers certain characteristics of the document object.

Methods are ready made functions of JavaScript,

that apply to the properties of certain objects so that a certain task is accomplished.

Each property of an object has its own methods which are usually more than one.

Example: The ready made function close(), closes the active window. To accomplish that it must be applied to the object window. The statement window.close() constitutes altogether (object and function) the method of closing the window.

Functions are procedures the programmer makes

in order to be called to execute at a certain point of a program.

They can be executed once or at various times during the program (web document) execution. They can also accept parametric values which they process and return to the HTML document after being executed. The set of statements that constitute the procedure after the declaration of the function name must be enclosed within braces { ... }.

Example: We start with the key word function and give a name to the function.

function AlfaBeta() {statement1; ... statementN; }

2.2. Structured Programming

Structured programming

Ιt all began as the technology of allocating the procedures of programs , when it was made clear that in this way they would be easier understood and therefore maintained by other programmers who hadn't originally written them.

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 11: An introduction to JavaScript Scripting Programming

It treats the program as the main routine. The logical flow of this process follows the tree structure in the way that each subroutine executes a certain part of the program at the level it operates. When the subroutine ends executing, the program flow returns to the main routine along with some processed variable values and then the following subroutine is called to execute and so on.

From within a subroutine of the main routine, another subroutine may be called to execute a different part of the program and from there another subroutine may be called and so on. In any case, the flow of the program returns to the level where the subroutine was called to execute.

In the example that follows we present a structured program that prints the payroll of a company.

The language used calls subroutines with the command CALL and returns the flow of the program where it was before calling the subroutine with Return.

The syntax of the language allows for arithmetic or nominal labels to branch the flow of the program along with the use of full stop (.) at the beginning of a line to indicate the comments that follow.

The names of the subroutines were chosen in a way that they declare what they actually do.

// .............................................. Main Routine (Level 1)

1. CALL "OpenFiles" //..... Opening the files

2. CALL "ReadMast" //..... Read Records

3. CALL "TestEOF" //..... Check for End Of File

4. CALL "Compute" //.... Conditional check & calculation of values

5. CALL "Print" //.... Printing the processed Record

6. GOTO 1 //.... Repetition of the main procedure

// .............................................. SubRoutines (Level 2)

OpenFiles // (code for opening the files) Return // ...............................

ReadMast // (code for reading records from the Master File) Return // ...............................

TestEOF // (code for checking of end of file) Return // ...............................

Compute CALL "Transactions" // Calculation of Overtime file Return .............................

Print CAll "TestPage" // Check for the end of page Return ............................

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 12: An introduction to JavaScript Scripting Programming

// ......... ...................................... SubRoutines (Level 3) Transactions CALL "TansEOF" // Check for end of Overtime file Return // ............................... TestPage {statement1; ... statementN;} // Code that prints a header in a new page) Return // ...............................

//................................................ SubRoutines (Level 4) TansEOF {statement1; ... statementN;} // (code for checking for end of Overtime file) Return // ...............................

2.3. Object Oriented Programming (OOP)

Object oriented programming 

It characterizes and handles both data and the procedures of handling data as objects with properties and methods through which these objects acquire values.

The properties or characteristics of objects are actually what make them function as autonomous entities.

These properties are essentially the object variables.

So, with certain methods, which are intrinsic functions of the language, we change the values of variables-properties of objects and with others we control the behavior of objects.

Object oriented programming languages must support :

1. Encapsulation 2. Classes 3. Inheritance 4. Polymorfism

Encapsulation,

concerns the protection of the values of object variables from the outside world. This means that the values of these object variables can change only through the methods of that object.

Classes, have to do with the levels of the structure of an object. Every object is an instance of a class.

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 13: An introduction to JavaScript Scripting Programming

Let's consider for example an HTML document as a document object. Our document therefore, as an object, lies in the upper class. Dividing it into three frames we create three new objects, one for each frame that are contained in the class of the document object.

If we create two new frames within the third frame, then the the third frame transforms into a class and the two embedded frames are the new objects it consists of.

Inheritance, through classes, transfers the values of the object properties to other objects.

In the previous example with classes and frames, we have given the upper class object , which is the document object, some properties with certain values, i.e. background color black bgcolor(black) and text color white text(white).

That means that all the objects of this class, which in our case are the three windows-frames on our screen (Frame1, Frame2 and Frame3), will inherit these properties with the respective values and every time they display some text as their content, it will be white characters on black background.

But the object Frame3 is a subclass at a lower level of the document object , since it is contained in it and has its own objects Frame3_1 and Frame3_2.

Consequently, the properties of the upper class are automatically transferred to the objects of lower classes in the hierarchy and therefore to their objects.

So, the windows-frames Frame3_1 and Frame3_2 will display their text in white characters on black background.

In JavaScript, inheritance and classes follow the parental tree of creation with reference from the parent class towards the children.

Our reference to the window frame Frame3_2 must follow the syntax :

parent.Frame3.Frame3_2 ... ;

We actually start our path from the upper class (document object), which JavaScript understands as parent, and we continue to the subclass Frame3 and its object Frame3_2, which we want to refer to.

Polymorphism, is the creation of several forms for the same object.In object oriented programming, every object is an instance of a certain class.

(Class) Document Object |

Frame1 Frame2 Frame3 (Subclass of class Document Object) |

Frame3_1 Frame3_2

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 14: An introduction to JavaScript Scripting Programming

The procedure of creating a new object is called instance initialization and is accomplished by applying a certain construction method.

The key word to create new objects in JavaScript is new. With this statement : myOnoma=new String("alex") we create a new instance of the object String, by applying the method String("alex"), which is stored in the variable myOnoma.This instance will have the value "alex.

In polymorfism, we actually create several methods for the same object under the same name. What changes is the number of their parameters. Referring to the previous example we may write :

myOnoma=new String("alex")

myOnoma=new String("alex","green")

myOnoma=new String("alex","green","131 52")

Each time we have a different definition of the specific object which is designated by the different number of the variables - parameters of the same method.

2.4. The element script and its attributes

The common way to include a Script program - a block of commands - in an HTML document is through the <script> tag. Within the tag we declare the Script language the program is written along with its version, so that the user's browser knows in which language the program will be parsed, as long as it supports this language.

With the closing tag </script>, the browser understands the end of the Script program and returns to the interpretation of HTML tags. An exception to the previous rule are the event handlers through which we execute programs or statements without using the <script> tag.

 

Note : HTML 4 version is the application based on the International Standard [ISO8879] of SGML . HTML is a set of tags for marking up documents which follows the rules of SGML.. DTD Transitional version of HTML is provided to HTML authors that use Tables and in their cells they apply occasionally several formatting and presentation patterns. The first statement in documents compiled under HTML Transitional DTD must be :

<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" >

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 15: An introduction to JavaScript Scripting Programming

2.4.1. The HTML element script

Τhe element Script, is an HTML element and is compiled as a markup element , either as a content of <head> ... </head> tags or within the body of an HTML document, i.e. as a content of <body> ... </body> tags.

Under no circumstances should the contents of the element Script be tags or other HTML elements. They should only be some Script language code which is going to be executed.

As with every HTML element, the Script element is characterized by attributes whose values are determined by the author of the HTML document.

For the Script element , both opening and closing tags are required.

2.4.2. The attributes of the element script

Its syntax contains the following arguments :

SRC (url) specifies the URL of an external Script TYPE (content type) specifies the MIME type of its contents LANGUAGE (character data) specifies the Script language DEFER (boolean) states that the Script must not be read and immediately executed.

The Script program is incorporated into the HTML document either as an external file through the src attribute ,whose values are the url and the name of the Script file, or directly within the document as the content of the <script> ... </script> tag.

The syntax within the Script element for a link to an external file is the following:

<script type="text/ecmascript" language="javascript" src="http://www.w3opensource.com/scripts/mast.js"> </script>

The syntax of embedding the Script program within the <script> ... </script> tag is the following :

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 16: An introduction to JavaScript Scripting Programming

<script type="text/ecmascript" language="javascript" <!-- timeday = new Date(); document.write(' Today is :' + timeday.toString() ) //--> </script>

Fourth generation browsers onwards (IE 4.0+, NN 4.0+) support SRC (url) attribute and the link to an external JavaScript file. Declaring the TYPE (content type) attribute is optional. It's mandatory to declare the LANGUAGE (character data) attribute which refers to the Script language the Script is written as well as its version.

2.4.3. Hiding the Scripts within comments

The technique of hiding Script programs within the marking of HTML comments ,aims to make Scripts appear as comments to older browsers that don't support the element Script and therefore don't support Script languages.

<script Language="JavaScript"> <!-- // Start hiding document.write("Good morning Universe !"); // Stop hiding --> </script>

In the previous example, a browser that does not support Javascript will not display the respective message of the Script and will interpret it as an HTML comment , as long as this is within <!-- and -->.

The two slashes denote JavaScript comment to what follows. The comment slashes of JavaScript must be put before the end of comment --> of HTML, so that they are are not interpreted as JavaScript statement and therefore , as unacceptable code, cause an error.

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 17: An introduction to JavaScript Scripting Programming

3. Embedding Scripts within HTML documents

The way of embedding JavaScript code within HTML documents depends on the web browsers called to parse the code and bring out the features of the language.

That means that different browsers interpret in a different way the elements and features of the language.

The incompatibility of web browsers concerning JavaScript led the European Computer Manufacturers Association ECMA to develop the ECMA-262 standard as the international standard of JavaScript syntax and formatting.

Nevertheless, some browsers launched before the development of ECMA-262 support the SRC(url) attribute and the link to an external JavaScript file and some others don't. Furthermore, some support the Layers technique while some don't.

3.1. Within the document body

The Script as a content of the main body, of the HTML document , can be embedded everywhere between <body> ... </body> you want. In the practice example below we create a JavaScript script inside the HTML document <body> ... </body> structure which executes the JavaScript built-in function that gives us the last date that the document is modified.

Let us see how simple is the logic to create and execute a script inside the body section of the HTML document.

Document:: LastModified.html

<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head><title>JavaScript within Body</title> <meta name="Author" content="A. Gklinos" /> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252" /> </head> <body> <h2>Web Scripting programming - JavaScript</h2> <script language="javascript" > <!-- document.write(document.lastModified); //--> </script> <p>Embedding JavaScript code within the body can be done at any part of it and as a content of the Script tags.</p> </body>

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 18: An introduction to JavaScript Scripting Programming

</html>

The Script is executed right after the appearance of header <h2> and the content of paragraph <p>. It consists of only one statement, document.write, which in JavaScript refers to output to the HTML document, and which in our case displays the value of the variable (document.lastModified), which provides the last date of the file modification.

3.2. In the first section of the page header

Τhe Script within the contents of the header tags <head> ... </head> is incorporated only within the first section of the HTML document and is called to execute from some part of <body> either through the Script tag or an event handler from within some HTML tag.

The Scripts contained in the first section of the HTML document and within the <head> ... </head> tags are usually functions we create so that the browser will execute them later from a certain point of the document body.

As in the following example :

Document: HelloScriptWorld.html:

<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head><title>JavaScript within Body</title> <meta name="Author" content="A. Gklinos" /> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252" /> <script language="javascript"> <!-- function Hello(onoma) { alert(' Hi,' + onoma); } //--></script> </head> <body> <h2>Web Scripting programming - JavaScript </h2> <p> <script language="javascript">Hello('Mary');</script> </p> <p>The Scripts contained in the first section of the HTML document and within the <head> ... </head> tags are usually functions we create so that the browser will execute them later from a certain point of the document body. </p> <p> <script language="javascript">Hello('Jane');</script> </p> </body> </html>

In the HTML document above we have three Scripts, one with the main code that creates the function Hello(onoma) inside <head>... </head> , and two Scripts within the document body that call the function.

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 19: An introduction to JavaScript Scripting Programming

The JavaScript functions are called by their name from within Scripts, including the parentheses and the variable values, if they have any. In our example, we called the function Hello(onoma) twice, with values "Mary" and "Jane" respectively.

When the function is called to execute, the browser transfers control to the first statement of the function carrying the value it will assign its parameter.

When the message appears, JavaScript will suspend execution until the user clicks OK and then it continues.

3.3. Within HTML tags by an event handler

The Script can be set as value in an event handler   and is called to execute as response of this specific event handler when the respective event is taken place.

The script is created in the first section of the HTML document within the <head> ... </head>. In our example below we write a script in the first section of our document which is called to execute by the event handler "OnClick" in the <input> tag which refers to an HTML form.

As in the following example :

Document:: Script_by_EventHandler.html

<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title> Calling a Script by an event handler</title> <meta name="Author" content="A. Gklinos" /> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252" /> <script language="javascript"> <!-- Start hiding function TextBox(text) { alert(text); } //Stop hiding --> </script> </head> <body> <form> <input type="text" name="poem" size="30" /> <input type="button" name="b1" value="Click !" onClick="TextBox(form.poem.value )" /> </form> </body> </html>

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 20: An introduction to JavaScript Scripting Programming

In this example, we call the function TextBox(text) through the event handler OnClick, when the user clicks on the certain button which we have associated OnClick with. Then the function executes having as a value for the variable (text), the value it received through the OnClick event handler, by the execution of the statement form.poem.value .

3.4. Calling an external file through the <script> tag

The most popular browsers, Internet Explorer and Netscape Navigator, since their 4.0+ and 3.0+ versions respectively support the attribute src(url) of the element Script to link an HTML document to external JavaScript files.

Let as create an HTML document which is connected with an external JavaScript file through the src attribute (property) of the HTML <script> tag. Look at the complete syntax in the following example :

Document:: Script_by_EventHandler.html

<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Calling a Script from an external JavaScript file</title> <meta name="Author" content="A. Gklinos" /> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252" /> <script language="javascript" src="http://www.w3opensource.com/scripts/mast.js" > <!-- // loading file mast.js to cache memory --> </script></head> <body> <h2>Scripts with an external JavaScript file</h2> <p>In the present document we apply JavaScript navigational techniques.. The Script in the file "mast.js" contains only JavaScript code and no HTML tag markup. It is loaded by the browser in the first section of the document between the <head> tags.</p> <p>The Script consists of a table that contains in its fields the respective links for each web page, and two functions ToForward() and ΤοBack(), which , when called, move us to the next or respective web page.</p> <p>The functions are called and executed through the tag (a) as hyperlinks, with the attribute href="javascript:functionName". </p> <a href="javascript:ΤοBack()">Previous page</a><br /> <a href="javascript:ToForward()">Next page</a><br /> </body> </html>

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 21: An introduction to JavaScript Scripting Programming

The Script in the file "mast.js" contains only JavaScript code and no HTML tag markup.

It is loaded by the browser in the first section of the document between the <head>... </head> tags.

The Script consists of a table that contains in its fields the respective links for each web page, and two functions ToForward() and ToBack(), which, when called, move us to the next or respective web page.

The functions are called and executed through the tag (a) as hyperlinks, having as a value href="javascript:functionName" , each time the name of the function.

3.5. JavaScript comments

Inserting comments in JavaScript,  is mainly done for program documentation reasons, as this is demanded by the philosophy of developing programming applications. A programmer that respects himself, always documents his work by inserting comments in every part of the code he writes. The comments must help to understand the parts of the code they describe , and they should be distinct, specific and simple.

In JavaScript we use two slashes // to tell the browser that what follows till the end of the line is a comment and must be ignored.

JavaScript also supports the syntax for comments of the C language, that starts with a slash followed by an asterisk /* and ends with an asterisk followed by a slash */.

In between /* ... */, the programmer can include as many lines as he wishes.

This second type of including comments in more than one line is used in encoding other web programming technologies such as Cascading Style Sheets.

In the following example, we have an implementation of what was previously stated:

//what follows till the end of the line is a comment.

/* in more than one lines, the comments are enclosed between a slash and an asterisk - just as in C language. */

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved

Page 22: An introduction to JavaScript Scripting Programming

.

An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce

Copyright © w3opensource.com All rights reserved