Java Script Overview Overview About Basics Objects DOM

Java. Script Overview

Overview About Basics Objects DOM 2

About Java. Script is not Java, The original name for Java. Script was “Live. Script” The name was changed when Java became popular Now that Microsoft no longer likes Java, its name for their Java. Script dialect is “Active Script” Statements in Java. Script resemble statements in Java, because both languages borrowed heavily from the C language Java. Script should be fairly easy for Java programmers to learn However, Java. Script is a complete, full-featured, complex language Java. Script is seldom used to write complete “programs” Instead, small bits of Java. Script are used to add functionality to HTML pages Java. Script is often used in conjunction with HTML “forms” Java. Script is reasonably platform-independent 3

Javascript --- 2 kinds? ? ? Java. Script Runs on client Node. JS (not the topic of this lecture) NEW Runs on server 4

Java. Script (client side) Allows Interactivity �Improve appearance �Especially graphics �Visual feedback �Site navigation �Perform calculations �Validation of input �Other technologies javascript. internet. com

Why talk about Java. Script? �Very widely used, and growing �Web pages, AJAX, Web 2. 0 �Increasing number of web-related applications �Some interesting and unusual features �First-class functions - interesting �Objects without classes - slightly unusual �Powerful modification capabilities - very unusual �Add new method to object, redefine prototype, access caller … �Many security, correctness issues �Not statically typed – type of variable may change … �Difficult to predict program properties in advance

Using Java. Script in a browser Java. Script code is included within <script> tags: <script type="text/javascript"> document. write("<h 1>Hello World!</h 1>") ; </script> Notes: The type attribute is to allow you to use other scripting languages (but Java. Script is the default) This simple code does the same thing as just putting <h 1>Hello World!</h 1> in the same place in the HTML document The semicolon at the end of the Java. Script statement is optional You need semicolons if you put two or more statements on the same line It’s probably a good idea to keep using semicolons 7

Java. Script isn’t always available Some old browsers do not recognize script tags These browsers will ignore the script tags but will display the included Java. Script To get old browsers to ignore the whole thing, use: <script type="text/javascript"> <!-document. write("Hello World!") //--> </script> The <!-- introduces an HTML comment To get Java. Script to ignore the HTML close comment, -->, the // starts a Java. Script comment, which extends to the end of the line 8 Some users turn off Java. Script Use the <noscript>message</noscript> to display a message in place of whatever the Java. Script would put there

Where to put Java. Script can be put in the <head> or in the <body> of an HTML document Java. Script functions should be defined in the <head> This ensures that the function is loaded before it is needed Java. Script in the <body> will be executed as the page loads Java. Script can be put in a separate. js file <script src="my. Java. Script. File. js"></script> Put this HTML wherever you would put the actual Java. Script code An external. js file lets you use the same Java. Script on multiple HTML pages The external. js file cannot itself contain a <script> tag Java. Script can be put in an HTML form object, such as a button This Java. Script will be executed when the form object is used 9

welcome. html (1 of 1) HTML comment tags will result in skipping of the script by those browsers that do not support scripting

welcome 2. html (1 of 1) Escape character in combination with quotation mark: ” will result in insertion of a quotation mark in the string that is actually written by Java. Script

welcome 3. html 1 of 1 New line of the html document in a browser is determined by an html element

Java. Script Variables are not typed ---you simply use them –no need to declare type show_info = new Boolean(true); Year = "2002"; var Name = "Butch"; //instance variable var Age = 6; //instance variable. . Age ="Six Years"; //this is legal to change. . 13 Instance Variables: • only accessible in the current function (or if not inside a function, the current script) • use the special keyword: var • Variables not declared as instance variables (preceeded by var), are accessible potentially anywhere

Literals --- data types Java. Script has three “primitive” types: number, string, and boolean Everything else is an object Numbers are always stored as floating-point values Hexadecimal numbers begin with 0 x Some platforms treat 0123 as octal, others treat it as decimal Since you can’t be sure, avoid octal altogether! Strings may be enclosed in single quotes or double quotes Strings can contains n (newline), " (double quote), etc. Booleans are either true or false 0, "0", empty strings, undefined, null, and Na. N are false , other values are true 14

Variables names must begin with a letter or underscore names are case-sensitive Variables are untyped (they can hold values of any type) var is optional (but it’s good style to use it) Variables declared within a function are local to that function (accessible only within that function) Variables declared outside a function are global (accessible from anywhere on the page) 15

Operators, I Because most Java. Script syntax is borrowed from C (and is therefore just like Java), we won’t spend much time on it Arithmetic operators (all numbers are floating-point): + * / % ++ - Comparison operators: < <= == != >= > Logical operators: && || ! (&& and || are short-circuit operators) Bitwise operators: & | ^ ~ << >> >>> Assignment operators: += -= *= /= %= <<= >>>= &= ^= |= 16

Operators, II String operator: + The conditional operator: condition ? value_if_true : value_if_false Special equality tests: == and != try to convert their operands to the same type before performing the test === and !== consider their operands unequal if they are of different types Additional operators (to be discussed): new 17 typeof void delete

Operators Always use parentheses to ensure desired order of evaluation: (a + b) / 6

Comments are as in C or Java: Between // and the end of the line Between /* and */ Java’s javadoc comments, /**. . . */, are treated just the same as /*. . . */ comments; they have no special meaning in Java. Script 19

Example: simple calculation <html> … <p> … </p> <script> var num 1, num 2, sum num 1 = prompt("Enter first number") num 2 = prompt("Enter second number") sum = parse. Int(num 1) + parse. Int(num 2) alert("Sum = " + sum) </script> … </html>

Statements, I Most Java. Script statements are also borrowed from C Assignment: greeting = "Hello, " + name; Compound statement: { statement; . . . ; statement } If statements: if (condition) statement; else statement; Familiar loop statements: while (condition) statement; do statement while (condition); for (initialization; condition; increment) statement; 21

Statements, II The switch statement: switch (expression) { case label : statement; break; . . . default : statement; } Other familiar statements: break; continue; The empty statement, as in ; ; or { } 22

Java. Script is not Java By now you should have realized that you already know a great deal of Java. Script So far we have talked about things that are the same as in Java. Script has some features that resemble features in Java: Java. Script has Objects and primitive data types Java. Script has qualified names; for example, document. write("Hello World"); Java. Script has Events and event handlers Exception handling in Java. Script is almost the same as in Java. Script has some features unlike anything in Java: Variable names are untyped: the type of a variable depends on the value it is currently holding Objects and arrays are defined in quite a different way Java. Script has with statements and a new kind of for statement 23

Array literals You don’t declare the types of variables in Java. Script has array literals, written with brackets and commas Example: color = ["red", "yellow", "green", "blue"]; Arrays are zero-based: color[0] is "red" If you put two commas in a row, the array has an “empty” element in that location Example: color = ["red", , , "green", "blue"]; color has 5 elements However, a single comma at the end is ignored Example: color = ["red", , , "green", "blue”, ]; still has 5 elements 24

Arrays created Simply define a variable to be an array and call the built-in Java. Script class Array's constructor as follows: var Names = new Array(3); //says there will 3 elements in the array for(var i=0; i<Names. length; i++) //initially all names to a dummy string Names[i] = "Unknown"; //Alternative declaration var Names = new Array("Unknown", "Unknown"); 25

Four ways to create an array You can use an array literal: var colors = ["red", "green", "blue"]; You can use new Array() to create an empty array: var colors = new Array(); You can add elements to the array later: colors[0] = "red"; colors[2] = "blue"; colors[1]="green"; You can use new Array(n) with a single numeric argument to create an array of that size var colors = new Array(3); You can use new Array(…) with two or more arguments to create an array containing those values: var colors = new Array("red", "green", "blue"); 26

The length of an array If my. Array is an array, its length is given by my. Array. length Array length can be changed by assignment beyond the current length Example: var my. Array = new Array(5); my. Array[10] = 3; Arrays are sparse, that is, space is only allocated for elements that have been assigned a value Example: my. Array[50000] = 3; is perfectly OK But indices must be between 0 and 232 -1 As in C and Java, there are no two-dimensional arrays; but you can have an array of arrays: my. Array[5][3] 27

Arrays and objects Arrays are objects car = { my. Car: "Saturn", 7: "Mazda" } car[7] is the same as car. 7 car. my. Car is the same as car["my. Car"] If you know the name of a property, you can use dot notation: car. my. Car If you don’t know the name of a property, but you have it in a variable (or can compute it), you must use array notation: car["my" + "Car"] 28

Array functions If my. Array is an array, my. Array. sort() sorts the array alphabetically my. Array. sort(function(a, b) { return a - b; }) sorts numerically my. Array. reverse() reverses the array elements my. Array. push(…) adds any number of new elements to the end of the array, and increases the array’s length my. Array. pop() removes and returns the last element of the array, and decrements the array’s length my. Array. to. String() returns a string containing the values of the array elements, separated by commas 29

The for…in statement You can loop through all the properties of an object with for (variable in object) statement; Example: for (var prop in course) { document. write(prop + ": " + course[prop]); } Possible output: teacher: Dr. Dave number: CIT 597 The properties are accessed in an undefined order If you add or delete properties of the object within the loop, it is undefined whether the loop will visit those properties Arrays are objects; applied to an array, for…in will visit the “properties” 0, 1, 2, … Notice that course["teacher"] is equivalent to course. teacher You must use brackets if the property name is in a variable 30

The with statement with (object) statement ; uses the object as the default prefix for variables in the statement For example, the following are equivalent: with (document. my. Form) { result. value = compute(my. Input. value) ; } document. my. Form. result. value = compute(document. my. Form. my. Input. value); One of my books hints at mysterious problems resulting from the use of with, and recommends against ever using it 31

Functions should be defined in the <head> of an HTML page, to ensure that they are loaded first The syntax for defining a function is: function name(arg 1, …, arg. N) { statements } The function may contain return value; statements Any variables declared within the function are local to it The syntax for calling a function is just name(arg 1, …, arg. N) Simple parameters are passed by value, objects are passed by reference 32

More about functions � Declarations can appear in function body �Local variables, “inner” functions � Parameter passing �Basic types passed by value, objects by reference � Call can supply any number of arguments �functionname. length : # of arguments in definition �functionname. arguments. length : # args in call � “Anonymous” functions (expressions for functions) �(function (x, y) {return x+y}) (2, 3);

Function Examples � Anonymous functions make great callbacks set. Timeout(function() { alert("done"); }, 10000) � Variable number of arguments function sum. All() { var total=0; for (var i=0; i< sum. All. arguments. length; i++) total+=sum. All. arguments[i]; return(total); } sum. All(3, 5, 3, 2, 6)

Exception handling, I Exception handling in Java. Script is almost the same as in Java throw expression creates and throws an exception The expression is the value of the exception, and can be of any type (often, it's a literal String) try { statements to try } catch (e) { // Notice: no type declaration for e exception handling statements } finally { // optional, as usual code that is always executed } With this form, there is only one catch clause 35

Exception handling, II try { } } statements to try catch (e if test 1) { exception handling for the case that test 1 is true catch (e if test 2) { exception handling for when test 1 is false and test 2 is true catch (e) { exception handling for when both test 1 and test 2 are false finally { // optional, as usual code that is always executed } Typically, the test would be something like e == "Invalid. Name. Exception" 36

Regular expressions A regular expression can be written in either of two ways: Within slashes, such as re = /ab+c/ With a constructor, such as re = new Reg. Exp("ab+c") Regular expressions are almost the same as in Perl or Java (only a few unusual features are missing) string. match(regexp) searches string for an occurrence of regexp It returns null if nothing is found If regexp has the g (global search) flag set, match returns an array of matched substrings If g is not set, match returns an array whose 0 th element is the matched text, extra elements are the parenthesized subexpressions, and the index property is the start position of the matched substring 37

Objects in Java. Script 38

Java. Script: Object-Based Language � There are three object categories in Java. Script: Native Objects, Host Objects, and User-Defined Objects. �Native objects: defined by Java. Script. � String, Number, Array, Image, Date, Math, etc. �Host objects : supplied and always available to Java. Script by the browser environment. � window, document, forms, etc. �User-defined objects : author/programmer defined by the

User defined Classes/Objects How to create your own 40

Object literals You don’t declare the types of variables in Java. Script has object literals, written with this syntax: { name 1 : value 1 , . . . , name. N : value. N } Example (from Netscape’s documentation): car = {my. Car: "Saturn", 7: "Mazda", get. Car: Car. Types("Honda"), special: Sales} The fields are my. Car, get. Car, 7 (this is a legal field name) , and special "Saturn" and "Mazda" are Strings Car. Types is a function call Sales is a variable you defined earlier Example use: document. write("I own a " + car. my. Car); 41

Three ways to create an object You can use an object literal: var course = { number: "CIT 597", teacher: "Dr. Dave" } You can use new to create a “blank” object, and add fields to it later: var course = new Object(); course. number = "CIT 597"; course. teacher = "Dr. Dave"; You can write and use a constructor: function Course(n, t) { // best placed in <head> this. number = n; // keyword "this" is required, not optional this. teacher = t; } var course = new Course("CIT 597", "Dr. Dave"); 42

BOM, DOM and more “Host objects” 43

Browser Object Model �The BOM defines the components and hierarchy of the collection of objects that define the browser window. �For the most part, we will only be working with the following components of the BOM. • window object • location object • history object • document object • navigator object • screen object

Window Object �Top level in the BOM �Allows access to properties and method of: �display window �browser itself �methods thing such as error message and alert boxes �status bar Window object Navigator object Location object History object Document object Screen object

Document Object �Top of the Document Object Model (DOM). �This is probably the one you’ll use most. �Allows access to elements of the displayed document such as images and form inputs. �The root that leads to the arrays of the document: forms[ ] array, links[ ] array, and images[ ] array. �Least compliance to standard here – Netscape 6, Opera 6, and Mozilla 1. 0 are the best.

Navigator Object �Provides access to information and methods regarding the client’s browser and operating system. �Commonly used to determine client’s browser capabilities so page can be modified real time for best viewing. �Example: A script may check the browser type in order to modify CSS styles.

History Object �Provides access to the pages the client has visited during the current browser session. �Methods such as back() and forward() can be used to move through the history. �Can also be used to jump to any point in the history. �As with any browser history, it only allows for a single path.

Other BOM Objects �Location Object – Provides access to and manipulation of the URL of the loaded page. �Screen Object – Provides access to information about the client’s display properties such as screen resolution and color depth. �More information can be found at: http: //javascript. about. com/library/bltut 22. htm http: //www-128. ibm. com/developerworks/web/library/wa-jsdom/

Document Object Model �Document is modeled as a tree. �DOM Changes based on page displayed. Example: <html> <head> <title>My Page</title> </head> head <body> <h 1>My Page</h 1> <p name=“bob” id=“bob”> title Here’s the first paragraph. </p> <p name=“jim” id=“jim”> Here’s the second paragraph. </p> </body> </html> html body h 1 p bob • Another example can be found at: http: //oopweb. com/Java. Script/Documents/jsintro/Volume/part 2. htm jim

DOM Modeled as a tree 51

welcome 4. html 1 of 1 alert method of the window object displays a Dialog box Example using window object


welcome 5. html (1 of 2) Java. Script is a loosely typed language. Variables take on any data type depending on the value assigned. Value returned by the prompt method of the window object is assigned to the variable name “+” symbol can be used for text concatenation as well as arithmetic operator More using window object -> prompt


When the user clicks OK, the value typed by the user is returned to the program as a string. This is the prompt to the user. This is the default value that appears when the dialog opens. This is the text field in which the user types the value. If the user clicks Cancel, the null value will be returned to the program and no value will be assigned to the variable.

Another example using window object Simple Script Example: Adding Integers � The values of numbers to be added are obtained as user inputs colleted through the window. prompt method � parse. Int �Converts its string argument to an integer �What happens if the conversion is not done? � See example on our web site (not a number): value returned if non-numerical values are passed to the pares. Int method � Na. N

Addition. html (1 of 2)

Addition. html (2 of 2)


Java. Script Alert window <html> <head><title>My Page</title></head> <body> <p> <a href="myfile. html">My Page</a> <a href="myfile. html" on. Mouseover="window. alert('Hello'); "> My Page</A> </p> Java. Script written </body> An Event inside HTML </html>

HTML Forms and Java. Script Using DOM 62

HTML Forms and Java. Script �Java. Script is very good at processing user input in the web browser �HTML <form> elements receive input �Forms and form elements have unique names �Each unique element can be identified �Uses Java. Script Document Object Model (DOM)

Naming Form Elements in HTML <form name="addressform"> Name: <input name="yourname"> Phone: <input name="phone"> Email: <input name="email"> </form>

Forms and Java. Script document. formname. elementname. value Thus: document. addressform. yourname. value document. addressform. phone. value document. addressform. email. value

Using Form Data Personalising an alert box <form name="alertform"> Enter your name: <input type="text" name="yourname"> <input type="button" value= "Go" on. Click="window. alert('Hello ' + document. alertform. yourname. value); "> </form>

DOM and dynamic manipulation An example 67

Events –you can based on triggered events run Java. Script (event handling) code �Examples of events for your HTML pages include: �on. Load �on. Click �on. Mouse. Over �on. Mouse. Out �Each of these events can execute a script. �Events must be placed in a tag. For example: <a href="somesite. htm" on. Click = "javascript: function(); ">link text</a>

ALSO You can add or change elements on a page � Some possibilities �create. Element(element. Name) �create. Text. Node(text) �append. Child(new. Child) �remove. Child(node) � Example: Add a new list item: var list = document. get. Element. By. Id(‘list 1') var newitem = document. create. Element('li') var newtext = document. create. Text. Node(text) list. append. Child(newitem) newitem. append. Child(newtext) This example uses the browser Document Object Model (DOM).
- Slides: 69