An introduction to JavaScript Scripting Programming
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

An introduction to JavaScript Scripting Programming

on

  • 2,144 views

An introduction to JavaScript Scripting Programming

An introduction to JavaScript Scripting Programming

Statistics

Views

Total Views
2,144
Views on SlideShare
2,141
Embed Views
3

Actions

Likes
2
Downloads
50
Comments
0

2 Embeds 3

http://192.168.6.179 2
http://www.slideshare.net 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

An introduction to JavaScript Scripting Programming Document Transcript

  • 1. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-CommerceThis 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 NewsletterTo purchase the full licensed version - click on the button Copyright © w3opensource.com All rights reserved
  • 2. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce       An Introduction to Teach Yourself  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 in 6 hours 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 Copyright © w3opensource.com All rights reserved
  • 3. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce      An Introduction to JavaScript Scripting ProgrammingLearning An Introduction to JavaScript Scripting Programmingyou will be able to understand how do you create and embed JavaScript scripts to yourdocuments for more dynamic presentation.You will know the structure of the language and how do you organize your scripts and the orderof 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 Users Browser compatibility How to define the scripting language of your scripts Copyright © w3opensource.com All rights reserved
  • 4. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce 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 Copyright © w3opensource.com All rights reserved
  • 5. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce 1. Web Scripting Programming The inability of HTML to cover the needs of interactivitybetween an internet user and a web page of a site being visited, gave birth to Scriptprogramming languages.With a Script programming language a web programmer or an author of an HTML documentcan incorporate script programs into the HTML code of his documents so that, when they areinterpreted and parsed by the users browser, a communication of the form question-responseis 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 theusers browser will execute, when the user downloads our site to his system or when the usersbrowser 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 owncomputer and is interpreted by his browser. In the second case we refer to Scriptingprogramming done on behalf of the web server, the computer that accommodates our webdocuments or web applications which are executed there and their responses or results aresent to the client browser.In any case, Script programming languages are interpreted languages by the browsers. When ausers browser asks for an HTML document with embedded JavaScript code from a webserver , 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 theusers browser downloads the document, it is parsed from top to bottom, interpreting every lineand displaying HTML tags and JavaScript statements as they are encountered. 1.1. Client-Side ScriptingWhen we create an HTML document,intending to incorporate Script programs in it, we must have decided beforehand whichScripting 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. Its 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 Copyright © w3opensource.com All rights reserved
  • 6. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce 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-262standard 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 thebrowser (client-side).Given that 99% of the web users internationally use the most popular browsers, InternetExplorer 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 theweb pages they choose on the internet must be written in a Script language their browsersupports, 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 ScriptingWhen it comes to Web Server Scripting programming,the languages used may be different from the ones the users browsers support.The reason is quite simple; the server Script programs are executed only on the server side andtheir results is what the users browser displays on the screen. The most widely used WebServer Scripts or interface programs are CGI (Common Gateway Interface) Scripts, written inScript 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 Copyright © w3opensource.com All rights reserved
  • 7. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerceprogramming on the Server Side.Since ASP technology of Microsoft supports JavaScript, the scripts that are embedded in thepages executed on the client side, can be written in JavaScript and the scripts executed on theweb 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), thatcan be chosen and used on the server side, you must know that in both cases the HTML pagesalong with Server-side JavaScript code they may contain are compiled into executable bytecode. This means that the web server that accommodates and parses these pages mustcontain the JavaScript runtime engine.When the users browser asks from the server a JSP or SSJS page, the server finds therelevant executable code page and reproduces it dynamically in HTML, which HTML page isfinally 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 maintainapplications.1.3. JavaScript versionsJavaScript is a  Web Scripting language developed by Netscape. Its original name was LiveScript and was first launched in 1995 along with Netscape Navigator2.0.JavaScript as an Interpreted Script programming language, intends to incorporate in HTMLdocuments features such as : graphics, sound, animation effects, video and interaction with the user in very manyways.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.0As 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 users browser. Detecting the users browser and cross browsing to a different part of a page. Interactive banners. Interactive pictures or graphics. Copyright © w3opensource.com All rights reserved
  • 8. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce   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 JavaJavaScript Is an interpreted language and not compiled. The JavaScript interpreter depends on the users 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 isno need to declare all variables, classes, and methods. Also you do not have to worry whethermethods are public, private, or protected. Additionally you do not have to declare variables andimplement 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 programminglanguage. The class-model of Java demands programs consist exclusively of classes and theirmethods. Additionally Javas class inheritance and object hierarchies as well as variablestyping declaration make Java more complex than JavaScript programming. Copyright © w3opensource.com All rights reserved
  • 9. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce 2. The structure of JavaScriptJavaScript statements are separated by a semicolon (;).These statements create variables, assign values to them, compare the contents of variablesand generally create and execute, step by step, the code of the program.As an integrated and object-oriented programming language - made by mathematicians- it isequipped with all the functions of a modern language, as: Variables, Operators Expressions Statements, Objects Events Event handlers Methods and FunctionsThe 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) Copyright © w3opensource.com All rights reserved
  • 10. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce 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 ProgrammingStructured programmingΙt all began as the technology of allocating the procedures of programs , when it was madeclear that in this way they would be easier understood and therefore maintained by otherprogrammers who hadnt originally written them. Copyright © w3opensource.com All rights reserved
  • 11. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-CommerceIt treats the program as the main routine.The logical flow of this process follows the tree structure in the way that each subroutineexecutes a certain part of the program at the level it operates. When the subroutine endsexecuting, the program flow returns to the main routine along with some processed variablevalues 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 adifferent 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 toexecute.In the example that follows we present a structured program that prints the payroll of acompany.The language used calls subroutines with the command CALL and returns the flow of theprogram 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 theprogram along with the use of full stop (.) at the beginning of a line to indicate the commentsthat 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 OvertimefileReturn .............................Print CAll "TestPage" // Check for the end of pageReturn ............................ Copyright © w3opensource.com All rights reserved
  • 12. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce// ......... ...................................... SubRoutines (Level 3)Transactions CALL "TansEOF" // Check for end of Overtime fileReturn // ...............................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 Overtimefile)Return // ............................... 2.3. Object Oriented Programming (OOP)Object oriented programming It characterizes and handles both data and the procedures of handling data as objects withproperties and methods through which these objects acquire values.The properties or characteristics of objects are actually what make them function asautonomous entities.These properties are essentially the object variables.So, with certain methods, which are intrinsic functions of the language, we change the values ofvariables-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. PolymorfismEncapsulation,concerns the protection of the values of object variables from the outside world. This means thatthe 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. Copyright © w3opensource.com All rights reserved
  • 13. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-CommerceLets 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 containedin the class of the document object.If we create two new frames within the third frame, then the the third frame transforms into aclass and the two embedded frames are the new objects it consists of. (Class) Document Object | Frame1 Frame2 Frame3 (Subclass of class Document Object) | Frame3_1 Frame3_2Inheritance,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 , whichis 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 onour screen (Frame1, Frame2 and Frame3), will inherit these properties with the respectivevalues and every time they display some text as their content, it will be white characters onblack background.But the object Frame3 is a subclass at a lower level of the document object , since it iscontained 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 oflower 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 onblack background.In JavaScript, inheritance and classes follow the parental tree of creation with reference fromthe 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 JavaScriptunderstands 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 objectis an instance of a certain class. Copyright © w3opensource.com All rights reserved
  • 14. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-CommerceThe procedure of creating a new object is called instance initialization and is accomplished byapplying 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 themethod String("alex"), which is stored in the variable myOnoma.This instance will have thevalue "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 maywrite : 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 thedifferent number of the variables - parameters of the same method.2.4. The element script and its attributesThe 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, sothat the users browser knows in which language the program will be parsed, as long as itsupports this language.With the closing tag </script>, the browser understands the end of the Script program andreturns to the interpretation of HTML tags.An exception to the previous rule are the event handlers through which we execute programs orstatements 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" > Copyright © w3opensource.com All rights reserved
  • 15. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce 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 HTMLelements.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 aredetermined 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 scriptIts 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 throughthe src attribute ,whose values are the url and the name of the Script file, or directly within thedocument 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 thefollowing : Copyright © w3opensource.com All rights reserved
  • 16. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce <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 linkto an external JavaScript file.Declaring the TYPE (content type) attribute is optional. Its mandatory to declare theLANGUAGE (character data) attribute which refers to the Script language the Script is writtenas well as its version. 2.4.3. Hiding the Scripts within commentsThe technique of hiding Script programswithin the marking of HTML comments ,aims to make Scripts appear as comments to olderbrowsers that dont support the element Script and therefore dont 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 therespective message of the Script and will interpret it as an HTML comment , as long as this iswithin <!-- 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, sothat they are are not interpreted as JavaScript statement and therefore , as unacceptable code,cause an error. Copyright © w3opensource.com All rights reserved
  • 17. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce 3. Embedding Scripts within HTML documentsThe way of embeddingJavaScript code within HTML documents depends on the web browsers called to parse thecode and bring out the features of the language.That means that different browsers interpret in a different way the elements and features of thelanguage.The incompatibility of web browsers concerning JavaScript led the European ComputerManufacturers Association ECMA to develop the ECMA-262 standard as the internationalstandard 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 dont. Furthermore,some support the Layers technique while some dont. 3.1. Within the document bodyThe Script as a content of the main body,of the HTML document , can be embedded everywhere between <body> ... </body> youwant.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 usthe 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 theHTML 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 ofit and as a content of the Script tags.</p> </body> Copyright © w3opensource.com All rights reserved
  • 18. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce </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 tothe 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 contentsof the header tags <head> ... </head> is incorporated only within the first section of theHTML document and is called to execute from some part of <body> either through the Script tagor 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 acertain 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 thefunction Hello(onoma) inside <head>... </head> , and two Scripts within the document bodythat call the function. Copyright © w3opensource.com All rights reserved
  • 19. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-CommerceThe JavaScript functions are called by their name from within Scripts, including the parenthesesand 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 thefunction carrying the value it will assign its parameter.When the message appears, JavaScript will suspend execution until the user clicks OK andthen it continues. 3.3. Within HTML tags by an event handlerThe 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 istaken 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 iscalled to execute by the event handler "OnClick" in the <input> tag which refers to an HTMLform.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> Copyright © w3opensource.com All rights reserved
  • 20. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-CommerceIn this example, we call the function TextBox(text) through the event handler OnClick, whenthe 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 receivedthrough the OnClick event handler, by the execution of the statement form.poem.value .3.4. Calling an external file through the <script> tagThe most popular browsers, Internet Explorer and NetscapeNavigator,since their 4.0+ and 3.0+ versions respectively support the attribute src(url) of the elementScript to link an HTML document to external JavaScript files.Let as create an HTML document which is connected with an external JavaScript file throughthe src attribute (property) of the HTML <script> tag. Look at the complete syntax in thefollowing 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 andno HTML tag markup. It is loaded by the browser in the first sectionof the document between the <head> tags.</p> <p>The Script consists of a table that contains in its fields therespective 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) ashyperlinks, 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> Copyright © w3opensource.com All rights reserved
  • 21. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-CommerceThe 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 orrespective web page.The functions are called and executed through the tag (a) as hyperlinks, having as a valuehref="javascript:functionName" , each time the name of the function. 3.5. JavaScript commentsInserting comments in JavaScript, is mainly done for program documentation reasons, as this is demanded by the philosophy ofdeveloping programming applications.A programmer that respects himself, always documents his work by inserting comments inevery part of the code he writes.The comments must help to understand the parts of the code they describe , and they shouldbe distinct, specific and simple.In JavaScript we use two slashes // to tell the browser that what follows till the end of the line isa comment and must be ignored.JavaScript also supports the syntax for comments of the C language, that starts with a slashfollowed 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 webprogramming 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. */ Copyright © w3opensource.com All rights reserved
  • 22. An Introduction to JavaScript Scripting Programming by Alex Gklinos MSc in E-Commerce. Copyright © w3opensource.com All rights reserved