Java Script Syntax 1 copyright Penny Mc Intire

  • Slides: 167
Download presentation
Java. Script Syntax 1 copyright Penny Mc. Intire, 2007

Java. Script Syntax 1 copyright Penny Mc. Intire, 2007

Java. Script Introduction • As we saw, Java. Script can be used to do

Java. Script Introduction • As we saw, Java. Script can be used to do such things as validating form data, so only valid data requires a trip to the server. • The advantage of doing validation in the browser is that it minimizes “chattiness” across the network. 2 copyright Penny Mc. Intire, 2007

Java. Script Introduction • The disadvantage is that including scripts in a document increases

Java. Script Introduction • The disadvantage is that including scripts in a document increases its initial download time – because it makes the HTML file larger. – Remedy? Create an external Java. Script file much like an external CSS file, if it’s to be used by more than one page. 3 copyright Penny Mc. Intire, 2007

Java. Script Introduction • Modern application architectures call for “thin” clients; i. e. ,

Java. Script Introduction • Modern application architectures call for “thin” clients; i. e. , the majority of the work is done on the server. – Some level of data validation on the client is appropriate. – Business logic on the client isn’t. 4 copyright Penny Mc. Intire, 2007

Java. Script Introduction • Since Java. Script is embedded as plain text in an

Java. Script Introduction • Since Java. Script is embedded as plain text in an html file, you can use Editpad (under Utilities in my public directory) to enter Java. Script into your HTML files or you can do it directly in Dreamweaver. • Use “View Source” frequently on the web; the best way to learn Java. Script is to look at scripts other people have written. 5 copyright Penny Mc. Intire, 2007

Java. Script Introduction • One of the coolest features of Java. Script is automatic

Java. Script Introduction • One of the coolest features of Java. Script is automatic garbage collection: de-allocation of memory when a variable is no longer needed. – This is done for you by the browser. 6 copyright Penny Mc. Intire, 2007

Java. Script Syntax • Java. Script syntax is easy – using Java. Script is

Java. Script Syntax • Java. Script syntax is easy – using Java. Script is not necessarily all that easy. • Although you'll learn much of the syntax of Java. Script in this class, you won't by any means learn the entire language or be able to create all kinds of fancy graphics flying around the screen – a whole semester all by itself. 7 copyright Penny Mc. Intire, 2007

Java. Script Introduction • Java. Script debugger built into Dreamweaver… – Click on the

Java. Script Introduction • Java. Script debugger built into Dreamweaver… – Click on the “world” icon and select “debug in …” and choose whichever browser you want to use for the test. – You can step into external files, set breakpoints, run to, step into, step over, etc. , just like a regular debugger. – Java. Script debugger tutorial http: //www. informit. com/articles/article. as 8 px? p=29739 debugger. copyright Penny Mc. Intire, 2007

Java. Script Syntax • First, let’s look at some Java. Script. . . (js

Java. Script Syntax • First, let’s look at some Java. Script. . . (js 01. html) 9 copyright Penny Mc. Intire, 2007

<html><head><title>fun with javascript, #1</title> <script language="Java. Script"> function my. First. Function() { alert(‘I've fallen

<html><head><title>fun with javascript, #1</title> <script language="Java. Script"> function my. First. Function() { alert(‘I've fallen and I can't get up!’); confirm(‘Will you help me? ’); prompt(‘How will you do that? ’, ‘I don’t know. ’); } </script> </head> This defines the function but doesn’t execute it. <body> <h 1>This shows an alert, a confirm, and a prompt. </h 1> <form> <input type=“submit" value="Click to try a JS Function” onclick="my. First. Function()"> The “onclick” event </form> executes the </body> function. </html>

Similarities to C syntax • If you know C/C++ (and all of you folks

Similarities to C syntax • If you know C/C++ (and all of you folks do), you know most of the Java. Script syntax. • So, first we are going to take a quick look at the syntax that is identical to C++, as a review… 11 copyright Penny Mc. Intire, 2007

Expressions and Operators • An expression is merely a phrase that the Java. Script

Expressions and Operators • An expression is merely a phrase that the Java. Script interpreter evaluates to produce a value. • Examples of expressions: – a variable name like my. Number – string literal ‘Hello World’ – numeric literal 89. 1 – Boolean literal true 12 copyright Penny Mc. Intire, 2007

Expressions and Operators • An operator is a symbol that is used to combine

Expressions and Operators • An operator is a symbol that is used to combine two or more expressions. • Mathematical operators… 13 copyright Penny Mc. Intire, 2007

Expressions and Operators +, -, *, / ++ -% +=, -= as we have

Expressions and Operators +, -, *, / ++ -% +=, -= as we have seen, but be careful with + (can be concatenation). increment by one, prefix and postfix ( ++my. Num or my. Num++ ) decrement by one, prefix and postfix ( - - my. Num or my. Num - - ) modulo; finds remainder (10 % 7 would be 3) add-by-value, subtract-by-value 14 copyright Penny Mc. Intire, 2007

Expressions and Operators • Careful with the “+” symbol – When used between two

Expressions and Operators • Careful with the “+” symbol – When used between two variables that Java. Script views as numbers, it is interpreted as the “plus” symbol. – In all other circumstances, it serves as a concatenation symbol. • 2 + 4 = 6 but “ 2” + 4 = “ 24” – Similarly, += is used to concatenate strings, not just for addition. – More on all this when we get into Java. Script data types. 15 copyright Penny Mc. Intire, 2007

Expressions and Operators • Let’s look at the other expressions and operators. . .

Expressions and Operators • Let’s look at the other expressions and operators. . . 16 copyright Penny Mc. Intire, 2007

Expressions and Operators == test for equality != test for inequality < less than

Expressions and Operators == test for equality != test for inequality < less than <= less than or equal to > greater than >= greater than or equal to ! not && logical and || logical or new create a new object 17 copyright Penny Mc. Intire, 2007

Expressions and Operators • == Evaluation of equality – == always resolves to a

Expressions and Operators • == Evaluation of equality – == always resolves to a boolean value. – Objects, including arrays, are evaluated by reference; that is, they are equal only if they refer to the same object. – So, two variables pointing to different arrays cannot ever be == even if they contain the exact same values. 18 copyright Penny Mc. Intire, 2007

Expressions and Operators • Comparisons: – Just like the Java language, Java. Script uses

Expressions and Operators • Comparisons: – Just like the Java language, Java. Script uses Unicode Character encoding, in which all upper case letters evaluate before all lower case letters. – Thus, “Horsefeathers” will be evaluated as less than (<) “balderdash. ” – Not like C, which uses the character set (such as ASCII) of the machine on which it is running. 19 copyright Penny Mc. Intire, 2007

Expressions and Operators • Operator precedence rules are the standard mathematical order of operations

Expressions and Operators • Operator precedence rules are the standard mathematical order of operations that you have used in other languages. • Be careful using the “+” symbol, especially with complex expressions using multiple operands; this is tricky. – Again, more on this later, when we look at data types. 20 copyright Penny Mc. Intire, 2007

Expressions and Operators • Rule of thumb: use parentheses and/or convert variables! • And

Expressions and Operators • Rule of thumb: use parentheses and/or convert variables! • And another thing…Java. Script statements end with a semi-colon. Not always required, but good programming practice. 21 copyright Penny Mc. Intire, 2007

Expressions and Operators • new (special object creation operator) – Used to instantiate objects

Expressions and Operators • new (special object creation operator) – Used to instantiate objects and arrays. – Must be used with a constructor call, such as Array () or Object(). – Examples: my. Array = new Array (2, 18, 21, 5) my. Object = new Object ( ) Puts these values in the array. 22 copyright Penny Mc. Intire, 2007

Control Structures • The basic form of an if-then statement: if (some condition) {

Control Structures • The basic form of an if-then statement: if (some condition) { do something; } else { do something else; } 23 copyright Penny Mc. Intire, 2007

Control Structures • Compound conditions use && (and) and || (or): if ((some condition)

Control Structures • Compound conditions use && (and) and || (or): if ((some condition) && (another condition)) { do something; } else { do something else; } 24 copyright Penny Mc. Intire, 2007

Control Structures • else if – used to implement a “case” structure using multiple

Control Structures • else if – used to implement a “case” structure using multiple variables; that is, more than two different conditions. 25 copyright Penny Mc. Intire, 2007

if ( input. Num = = ' ') { alert (' Please enter a

if ( input. Num = = ' ') { alert (' Please enter a valid number between 0 and 100. '); } else if ( input. Num <= 0 ) { alert (' Negative numbers and 0 are not allowed. '); } else if ( input. Num > 100 ) { alert (' Number is too large; please try again. '); } else { alert (' Thank you for entering a valid number. '); }

Control Structures • switch statement – used to implement a “case” structure when a

Control Structures • switch statement – used to implement a “case” structure when a single variable needs to be checked to determine which case to execute. • More efficient than the else if format for single variables, because each else if reevaluates the variable, while the switch evaluates the variable only once. 27 copyright Penny Mc. Intire, 2007

switch ( input. Num ) { case " " : do something #1; break;

switch ( input. Num ) { case " " : do something #1; break; case <= 0: do something #2; break; case > 100: do something #3; break; default: do something #4; break; } Required to terminate each case or statements in following cases will be executed, too. If nothing else matches.

Control Structures • The switch statement is much like the switch used in C,

Control Structures • The switch statement is much like the switch used in C, except Java. Script: – Allows strings, integers, floating-point numbers, and boolean fields as switch variables, not just integers. – Does not require case conditions to be all of the same type, because Java. Script is loosely-typed (more later). 29 copyright Penny Mc. Intire, 2007

Control Structures • while statement my. Count = 1; while ( my. Count <=

Control Structures • while statement my. Count = 1; while ( my. Count <= 10 ) { …do something… my. Count = my. Count +1 } 30 copyright Penny Mc. Intire, 2007

Control Structures • do/while statement – similar to a while statement, except it’s a

Control Structures • do/while statement – similar to a while statement, except it’s a bottom-driven loop. – Therefore, statements inside the loop are always executed at least once. – I don’t like this (my structured programming roots are showing). – If you want to use it, look it up for yourself. 31 copyright Penny Mc. Intire, 2007

Control Structures • for statement – Initialization, the test, and the increment/decrement of the

Control Structures • for statement – Initialization, the test, and the increment/decrement of the loop counter are all part of the syntax of the for. • More convenient to use than a while when you are looping based upon a counter. 32 copyright Penny Mc. Intire, 2007

Control Structures for( my. Ctr = 0 ; my. Ctr < 10 ; my.

Control Structures for( my. Ctr = 0 ; my. Ctr < 10 ; my. Ctr++ ) { …do something… } Will loop 10 times. 33 copyright Penny Mc. Intire, 2007

Comments • Comments – same as in C – // This is a single-line

Comments • Comments – same as in C – // This is a single-line comment – Java. Script here… //comment here – /* This is a multiple-line comment within a script. */ 34 copyright Penny Mc. Intire, 2007

Java. Script Variables 35 copyright Penny Mc. Intire, 2007

Java. Script Variables 35 copyright Penny Mc. Intire, 2007

Naming Conventions for Variables • The variable name must start with either a letter

Naming Conventions for Variables • The variable name must start with either a letter or an underscore character “_”. • All consecutive characters can be letters, numbers or underscore. • Important: Java. Script is case-sensitive, despite IE’s tendency to “assume” what you mean. • These naming conventions are also true 36 for function and placeholder names. copyright Penny Mc. Intire, 2007

Naming Conventions for Variables • Don’t use reserved words for identifiers. – Using a

Naming Conventions for Variables • Don’t use reserved words for identifiers. – Using a number with a word, or using multiple words strung together, is generally safe. – A few reserve words you might be tempted to use include case, default, function, return, switch, this, char, byte, double. • Names should be descriptive. (duh. ) 37 copyright Penny Mc. Intire, 2007

Global and Local Variables • A variable declaration inside of a function definition creates

Global and Local Variables • A variable declaration inside of a function definition creates a local variable, which means it is available only within that function. • A variable declaration outside of a function definition creates a global variable, which means it is available to the entire document. 38 copyright Penny Mc. Intire, 2007

Global and Local Variables • As with any language (other than our beloved COBOL),

Global and Local Variables • As with any language (other than our beloved COBOL), avoid global variables. – Local variables can step on the toes of global variables with the same name. – Of course, you wouldn’t think of assigning the same name to two different variables anyway, now would you? ! 39 copyright Penny Mc. Intire, 2007

Global and Local Variables • No block scope, as in C, C++, and Java.

Global and Local Variables • No block scope, as in C, C++, and Java. – Block scope means that the defined variable is available only within its containing block, which is bounded by { }. – This means that with other programming languages, you might have a variable that is available within, say, only one side of an if. – All local variables in Java. Script have function-wide scope, not block scope. 40 copyright Penny Mc. Intire, 2007

Variable Declaration • To declare a variable explicitly, use var my. Number; variable. Name

Variable Declaration • To declare a variable explicitly, use var my. Number; variable. Name 1, variable. Name 2; • These declare the variables but don’t assign values, which means they will be undefined until you assign values to them. 41 copyright Penny Mc. Intire, 2007

Variable Declaration • You can also assign a value when making a declaration: variable.

Variable Declaration • You can also assign a value when making a declaration: variable. Name 1 = 16, variable. Name 2 = ‘Error in input’, variable. Name 3 = 285. 03; 42 copyright Penny Mc. Intire, 2007

Variable Declaration • Here we see some basic math used to initialize a variable:

Variable Declaration • Here we see some basic math used to initialize a variable: var american. Dollars = exchange. Rate * irish. Pounds; • var declarations are technically optional; a variable will be created if you simply state a new variable name. var a = 0, b = 1; c = a + b; This creates a variable named “c” even though we haven’t explicitly used a var 43 declaration. copyright Penny Mc. Intire, 2007

Variable Declaration • But don’t “declare by omission”; it’s not only bad coding practice,

Variable Declaration • But don’t “declare by omission”; it’s not only bad coding practice, it makes an already ambiguously-typed language even harder to debug. • So, always explicitly declare your vars. 44 copyright Penny Mc. Intire, 2007

Data Typing • Some programming languages are strongly-typed; that is, a variable is set

Data Typing • Some programming languages are strongly-typed; that is, a variable is set as a particular type, and using it to store or manipulate data of a different type can cause problems. – For instance, C, C++, and COBOL are strongly-typed languages. – Many of you know what happens if you move character numbers (i. e. , “ 123”) into a COBOL PIC 999 field and then attempt to 45 do arithmetic! copyright Penny Mc. Intire, 2007

Data Typing • Java. Script is loosely-typed; that is, any variable can potentially hold

Data Typing • Java. Script is loosely-typed; that is, any variable can potentially hold any type of data. • So, you can alternate between treating a given data field as a number, string or boolean, if you want (not that you should!). 46 copyright Penny Mc. Intire, 2007

Data Typing • When you do so, as an intermediate step, Java. Script creates

Data Typing • When you do so, as an intermediate step, Java. Script creates a transient object which attempts to convert between the types. • More in a bit about how this all works and the default conversion rules. 47 copyright Penny Mc. Intire, 2007

var • So, a given var can “morph” into all my. String kinds of

var • So, a given var can “morph” into all my. String kinds of data. (Seems so wrong, Now but holds a get used to it!) numeric 12. var my. String = ‘Hi there. ’; my. String = 3 * 4; OR var Now my. String holds a numeric 6. my. String = ‘ 3’; my. String = my. String * 2 48 copyright Penny Mc. Intire, 2007

Java. Script Data Types • Data types in Java. Script – numbers – strings

Java. Script Data Types • Data types in Java. Script – numbers – strings – boolean 49 copyright Penny Mc. Intire, 2007

Conversion Rules • As I said earlier, Java. Script converts a var to the

Conversion Rules • As I said earlier, Java. Script converts a var to the appropriate data type based on how it’s being used. • To do so, Java. Script evaluates the expression to determine the output data type. • Big caution here: Java. Script uses specific conversion rules when evaluating an expression, which may not necessarily be what you intended an expression to be. • Here are those rules. . . 50 copyright Penny Mc. Intire, 2007

Conversion Rules • For the + sign: – If both variables are numbers, standard

Conversion Rules • For the + sign: – If both variables are numbers, standard addition is performed. • Examples: – 16 + 2 evaluates to 18 – If my. Field contains 23, my. Field + 8 evaluates to 31 51 copyright Penny Mc. Intire, 2007

Conversion Rules • For the + sign, continued: – If at least one of

Conversion Rules • For the + sign, continued: – If at least one of the elements is a string, both items will be treated as strings and concatenated. • Examples: – ‘ 16’ + ‘ 2’ evaluates to “ 162” – ‘ 3’ + 4 evaluates to “ 34” – If my. Field contains “ 23”, my. Field + 8 evaluates to “ 238” 52 copyright Penny Mc. Intire, 2007

Conversion Rules • For mathematical operators other than +, all strings will be converted

Conversion Rules • For mathematical operators other than +, all strings will be converted to numbers, if possible. – Examples: • ‘ 18’ / 3 evaluates to 6 (18 is converted to a number) • ‘ 2’ * ‘ 3’ evaluates to 6 (both are converted) • 2 * 4 evaluates to 8 (no conversion necessary) • ‘abc’ - 5 errors off (conversion is not possible) 53 copyright Penny Mc. Intire, 2007

Conversion Rules • With comparisons: – If one of the variables is a number,

Conversion Rules • With comparisons: – If one of the variables is a number, both variables are converted to numbers (if possible) and numeric comparison results. – If both are strings, a normal string comparison results. – Examples: • ‘ 33’ < 4 Numeric comparison because one of the two elements is a number; result is false. • ‘ 33’ < ‘ 4’ String comparison because neither element is a number; result is true. 54 copyright Penny Mc. Intire, 2007

Conversion Rules • Recap of rules: – With a +, strings take precedence and

Conversion Rules • Recap of rules: – With a +, strings take precedence and force concatenation. – With mathematical operators other than +, numbers take precedence. – With comparisons, numbers take precedence. • Even more concise recap: Strings take precedence only with + sign. 55 copyright Penny Mc. Intire, 2007

Conversion Rules • Be careful with complex expressions using multiple operands; whether items are

Conversion Rules • Be careful with complex expressions using multiple operands; whether items are converted from strings or not, and whether a + is used for addition or for concatenation, depends on the operator precedence. – 2 + 3 + ‘ 4’ evaluates to 54. – 2 + (3 + ‘ 4’) evaluates to 234. • Use parentheses and/or convert variables! 56 copyright Penny Mc. Intire, 2007

Conversion Rules • Rule of thumb: keep track of your own data types, and

Conversion Rules • Rule of thumb: keep track of your own data types, and convert them yourself when necessary. 57 copyright Penny Mc. Intire, 2007

Primitive Data Types • Again, there are three primitive data types in Java. Script:

Primitive Data Types • Again, there are three primitive data types in Java. Script: numbers, strings, and boolean. • Note: although these are primitive data types, and no data type is carved in stone, they can be “wrapped” in objects which contain conversion methods. 58 copyright Penny Mc. Intire, 2007

Numbers • Number objects do not distinguish between integers and floating-point (decimal) numbers. •

Numbers • Number objects do not distinguish between integers and floating-point (decimal) numbers. • All numbers are treated as floating-point when necessary. 59 copyright Penny Mc. Intire, 2007

Numbers • Number objects can represent numbers far larger than we will ever need

Numbers • Number objects can represent numbers far larger than we will ever need to use. • However, most integer manipulations are performed on 32 -bit numbers. • Can represent hex, octal, and scientific notation (but I’m not gonna go there). 60 copyright Penny Mc. Intire, 2007

Numbers • Special, abstract value Na. N means “not a number. ” – Results

Numbers • Special, abstract value Na. N means “not a number. ” – Results from such things as: • A user entering characters into an input field, even though you were expecting numbers. – Cannot test just to see if a number is equal to Na. N – it isn’t even equal to itself! – Instead, use the function is. Na. N() and test for true. 61 copyright Penny Mc. Intire, 2007

Numbers • To declare a var as an official Number object, var my. New.

Numbers • To declare a var as an official Number object, var my. New. Number = new Number(42); 62 copyright Penny Mc. Intire, 2007

Numbers • Why bother, when Java. Script is perfectly happy to do math on

Numbers • Why bother, when Java. Script is perfectly happy to do math on untyped vars? And when even Number objects such as this can hold strings and booleans? – Do this when you need to use the variable as an object, with methods and properties. 63 copyright Penny Mc. Intire, 2007

String Syntax • For representing and manipulating text. • To declare a var as

String Syntax • For representing and manipulating text. • To declare a var as a String object, var my. New. String = new String(“the string”); – Enclose the literal in matching pairs of single or double quotes. – Because Java. Script is embedded within html (which commonly uses double quotes), many experts believe it’s good practice to use single quotes for Java. Script. 64 copyright Penny Mc. Intire, 2007

String Syntax – I did that for these lectures, but I don’t necessarily agree.

String Syntax – I did that for these lectures, but I don’t necessarily agree. – I usually type double quotes outside (whether html or Java. Script), then start alternating as I hit inside quotes. 65 copyright Penny Mc. Intire, 2007

String Syntax • What if you want to use an apostrophe within a single-quoted

String Syntax • What if you want to use an apostrophe within a single-quoted string? • Use an escape sequence (“”) to use characters that already have meaning to Java. Script or that can’t be represented in any other way, such as the apostrophe… 66 copyright Penny Mc. Intire, 2007

String Syntax • Escape sequences use the  (backslash) character followed by another character.

String Syntax • Escape sequences use the (backslash) character followed by another character. • Common escape sequences ’ b ” n apostrophe backspace double quote new line \ r f t backslash carriage return form feed tab 67 copyright Penny Mc. Intire, 2007

String Syntax • Why bother declaring a string as a String object? – So

String Syntax • Why bother declaring a string as a String object? – So that you can use String’s associated methods and properties. – For instance, a var declared as a String object can be parsed to access, replace, or delete a substring. 68 copyright Penny Mc. Intire, 2007

Strings • Object contains multiple methods for doing common string manipulations, such as: –

Strings • Object contains multiple methods for doing common string manipulations, such as: – char. At(index) – index. Of(“char”) – substr(start, length) – search(reg. Exp) 69 copyright Penny Mc. Intire, 2007

String Syntax • To get the length of a string, use the length property:

String Syntax • To get the length of a string, use the length property: This is the variable for which we need the length. my. String. Length = my. Birthday. length This variable will hold the length after this command executes. This property of the my. Birthday object holds the length. 70 copyright Penny Mc. Intire, 2007

String Syntax • To progressively concatenate a long string, use the += operator. •

String Syntax • To progressively concatenate a long string, use the += operator. • For instance, if you have a whole paragraph of text to display, progressively add more of the text to the line variable by using successive += statement. my. String += ‘add this to the end’; my. String +=‘ and then add this on, too”; 71 copyright Penny Mc. Intire, 2007

Boolean • As with other languages, boolean contain only two values, true and false.

Boolean • As with other languages, boolean contain only two values, true and false. • Typically boolean values are used with a control statement such as an if. if (num 1 == 16) x = x + 1; else y = y + 1; Has a boolean value of true or false. 72 copyright Penny Mc. Intire, 2007

Boolean • To declare a var as a Boolean object, var my. New. Boolean

Boolean • To declare a var as a Boolean object, var my. New. Boolean = new Boolean(true|false) • Why bother? – As with Number and String objects, you do this when you need to use object properties with the variable. 73 copyright Penny Mc. Intire, 2007

Object Conversion • As we have now stated repeatedly, Java. Script is loosely-typed and

Object Conversion • As we have now stated repeatedly, Java. Script is loosely-typed and will convert variables between types according to it’s conversion rules. • However, it’s safer if we explicitly specify the conversions that we need. 74 copyright Penny Mc. Intire, 2007

Object Conversion to Number • Use the parse. Int() method to convert a String

Object Conversion to Number • Use the parse. Int() method to convert a String or Boolean to an integer (no rounding): – Example: var my. Result = parse. Int(my. String. Number, 10) + 23 – This converts whatever was in my. String. Number to an integer before doing the addition. An integer in base 10, usually the default. 75 copyright Penny Mc. Intire, 2007

Object Conversion to Number • In either case, the base number defaults to base

Object Conversion to Number • In either case, the base number defaults to base 10 if omitted, unless a leading zero in the number, in which case the number is converted to octal (!). • For a leading zero to be converted properly, you must specify the base as base 10. var my. Result = parse. Int(my. String. Number, 10) + 23 76 copyright Penny Mc. Intire, 2007

Object Conversion to Number • Use the parse. Float() method to convert a String

Object Conversion to Number • Use the parse. Float() method to convert a String or Boolean to a floating point (decimal) number: – Example: var my. Result = parse. Float(my. String. Number, 10) + 23. 1 – This converts whatever was in my. String. Number to a number with the appropriate decimal places. 77 copyright Penny Mc. Intire, 2007

Object Conversion to Number • When converting a boolean to a number using either

Object Conversion to Number • When converting a boolean to a number using either method, false will return 0 and true will return a non-zero value. • Note: any value captured from a form or a prompt window is viewed as a String – even if only digits were entered – unless you deliberately convert it. 78 copyright Penny Mc. Intire, 2007

Object Conversion to Number • Another way to convert a string number to a

Object Conversion to Number • Another way to convert a string number to a math number: Multiply by 1. • In any case, if you are at all in doubt about a field’s type or contents, convert it and test it against Na. N before attempting to use it as a number. 79 copyright Penny Mc. Intire, 2007

Object Conversion to String • To convert a Number to a String: – Concatenate

Object Conversion to String • To convert a Number to a String: – Concatenate it with an empty string: . . . (my. Num + ‘ ’ ). . . – Or use the to. String() method of the Number object. 80 copyright Penny Mc. Intire, 2007

Other DOM Objects • Other useful objects are predefined in the DOM to facilitate

Other DOM Objects • Other useful objects are predefined in the DOM to facilitate ease of programming, such as Array and Math. • First, let’s look at the Array object. 81 copyright Penny Mc. Intire, 2007

Array • An array is a collection of data values, accessible by a zero-based

Array • An array is a collection of data values, accessible by a zero-based index (first member is indexed by a zero value). – Just like most other languages (except COBOL). • Since Java. Script is loosely-typed, array elements can be of differing data types. This is different than strongly-typed languages, where an array type must be declared. 82 copyright Penny Mc. Intire, 2007

Array Syntax • Use square brackets to enclose the index: – my. Array [

Array Syntax • Use square brackets to enclose the index: – my. Array [ 2 ] gets the third member. – my. Array [ my. Index ] uses the value of my. Index to index the array. 83 copyright Penny Mc. Intire, 2007

Array Syntax • Creating arrays var my. Variable = 48 ; var my. Array

Array Syntax • Creating arrays var my. Variable = 48 ; var my. Array = new Array( ); my. Array[0] = ‘This is my array’; my. Array[1] = 86. 35; my. Array[2] = false; This is my array my. Array[3] = my. Variable; 86. 35 false 48 84 copyright Penny Mc. Intire, 2007

Array Syntax • The following gives the same results as previous example: var my.

Array Syntax • The following gives the same results as previous example: var my. Array = new Array(‘This is my array’, 86. 35, false, myvariable) – Can leave one or more elements undefined by simply omitting values between commas var my. Array = (‘This is my array’, 86. 35, , myvariable) undefined. 85 copyright Penny Mc. Intire, 2007

Array Syntax • Easiest way to represent a multidimensional array is to set up

Array Syntax • Easiest way to represent a multidimensional array is to set up multiple arrays in parallel. • Example: create a 50 -entry array for state names and a separate 50 -entry array for state capitals. – In each case, Alabama would be accessible by [0]. 86 copyright Penny Mc. Intire, 2007

Array Syntax • Can also simulate a multi-dimensional array with an array of arrays:

Array Syntax • Can also simulate a multi-dimensional array with an array of arrays: my. Array [index 1] [index 2] Complicated. • To add another element to an array: my. Array[my. Array. length] = “whatever” length property: if currently 4 entries, then this will add a 5 th entry. 87 copyright Penny Mc. Intire, 2007

Math Object • Another useful predefined object is the Math object, which contains a

Math Object • Another useful predefined object is the Math object, which contains a large library of commonly-used mathematical functions. Must be capitalized. • Examples: num 1 = = Math. sqrt(num 2) Math. ceil(num 2) Math. floor(num 2) Math. round(num 2) square root rounds num 2 up rounds num 2 down rounds by rule • For more math functions, see DHTML. 88 copyright Penny Mc. Intire, 2007

document. writeln() • document. writeln(parm) is used to dynamically output text into the page

document. writeln() • document. writeln(parm) is used to dynamically output text into the page as it loads into the browser. • Three types of parameters: – Text and/or html within quotes. document. writeln(‘With an exchange rate of ’); – Variables, not in quotes. document. writeln(irish. Pounds); – concatenated items (‘+’). document. writeln(american. Dollars + ‘ American dollars. ’); 89 copyright Penny Mc. Intire, 2007

inner. HTML • Allows you to access and manipulate the HTML inside of an

inner. HTML • Allows you to access and manipulate the HTML inside of an HTML container. var x=document. get. Element. By. Id("my. Header"); alert(x. inner. HTML); … <h 1 id="my. Header">Click me!</h 1> • The alert will display "Click me!" 90 copyright Penny Mc. Intire, 2007

document. writeln() • Let’s look at how this actually writes to the page from

document. writeln() • Let’s look at how this actually writes to the page from each line… 91 copyright Penny Mc. Intire, 2007

document. writeln(‘With an exchange rate of ’ + exchange. Rate + ‘, ’); With

document. writeln(‘With an exchange rate of ’ + exchange. Rate + ‘, ’); With an exchange rate of 1. 25 , document. writeln(irish. Pounds + ‘ Irish pounds are equal to ’); 150 Irish pounds are equal to document. writeln(american. Dollars + ‘ American dollars. ’); 187. 5 American dollars.

Null in Java. Script • Special value null means “no value” or “no object.

Null in Java. Script • Special value null means “no value” or “no object. ” • Signifies one of the following: – Using an object property that doesn’t exist. – Using a variable that doesn’t exist. • Example: c = a + b • If b has never been declared, both c and b are be null. • null in Java. Script is not zero; this is different from null in the C language. 93 copyright Penny Mc. Intire, 2007

Undefined in Java. Script • Special value undefined means you used a variable or

Undefined in Java. Script • Special value undefined means you used a variable or object property that doesn’t exist or that does exist but has never had a value assigned to it. • Note that this overlaps some of the circumstances which create a null value. 94 copyright Penny Mc. Intire, 2007

Undefined in Java. Script • In older versions of Java. Script, there was no

Undefined in Java. Script • In older versions of Java. Script, there was no undefined operator. – Instead, you would test for null (not really the same, but they evaluate as the same). • Newer versions of Java. Script use the undefined operator. • The most important use for both undefined and null is in interpreting messages given to you by the debugger 95 (translation: “Hey, idiot…”) copyright Penny Mc. Intire, 2007

Embedding Java. Script in HTML Documents • Java. Script script placement: – In an

Embedding Java. Script in HTML Documents • Java. Script script placement: – In an external. js file (just like. css files are externalized) that is called in the <head>. • Same benefits as an external. css file – it can be used by multiple documents and it is easier to maintain. • In the html file, within the <head>, specify <script language="Java. Script" src = "script. Name. And. Path. js"> </script> 96 copyright Penny Mc. Intire, 2007

Embedding Java. Script in HTML Documents • The external file is identical to a

Embedding Java. Script in HTML Documents • The external file is identical to a normal Java. Script script, except no <script>. . . </script>. • The file loads when the <head> loads, so – Java. Script outside of functions executes as the head loads. – Functions are loaded and ready to execute as soon as the <head> loads, but they don’t actually execute until invoked. 97 copyright Penny Mc. Intire, 2007

Embedding Java. Script in HTML Documents – In the <head> • Embed within <script

Embedding Java. Script in HTML Documents – In the <head> • Embed within <script language="Java. Script">. . . <script> • Java. Script outside of functions executes as the head loads. • Functions are loaded and ready to execute as soon as the <head> loads, but they don’t actually execute until invoked. 98 copyright Penny Mc. Intire, 2007

Embedding Java. Script in HTML Documents – In the <body> • As code associated

Embedding Java. Script in HTML Documents – In the <body> • As code associated with an event handler (like onclick) embedded in an html tag, or. . . • Embedded within <script language="Java. Script">. . . <script> – Used primarily to write “text” out to the page. – Executed as they are encountered in the HTML code. 99 copyright Penny Mc. Intire, 2007

Embedding Java. Script in HTML Documents • <script language="Java. Script"> – Specifying language="Java. Script"

Embedding Java. Script in HTML Documents • <script language="Java. Script"> – Specifying language="Java. Script" is technically optional because it is the default scripting language for all browsers; but do so anyway so there is no confusion with VBScript (currently the only other option). 100 copyright Penny Mc. Intire, 2007

Embedding Java. Script in HTML Documents – Can also include the Java. Script version

Embedding Java. Script in HTML Documents – Can also include the Java. Script version number with it, <script language="Java. Script 1. 1"> to specify which features to support. – Unless you really understand the differences between how the browsers implement the different versions, it’s safer to leave the version number off. 101 copyright Penny Mc. Intire, 2007

Example 1: A First Script • Let’s look at our first example of Java.

Example 1: A First Script • Let’s look at our first example of Java. Script. . . /Java. Script. Examples/js 01. html 102 copyright Penny Mc. Intire, 2007

<html><head><title>Fun with Java. Script, #1</title> <script language="Java. Script"> This defines function my. First. Function()

<html><head><title>Fun with Java. Script, #1</title> <script language="Java. Script"> This defines function my. First. Function() the function { but doesn’t alert(‘I've fallen and I can't get up!’); execute it. confirm(‘Will you help me? ’); prompt(‘How will you do that? ’, ‘I don’t know. ’); } </script> </head> • Type=“button” bypasses submitting the form. • The “onclick” event executes the function. <body> <h 1>This shows an alert box. </h 1> <form> <input type=“button" value="Click to try a JS Function” onclick="my. First. Function()"> </form> </body> </html>

Example 1: A First Script • Let’s look more closely at the function defined

Example 1: A First Script • Let’s look more closely at the function defined in the <head>… 104 copyright Penny Mc. Intire, 2007

Example 1: A First Script <script language="Java. Script"> // This function sequentially displays three

Example 1: A First Script <script language="Java. Script"> // This function sequentially displays three dialog boxes. This starts the function my. First. Function() function. { alert(‘I've fallen and I can't get up!’); confirm(‘Will you help me? ’); prompt(‘How will you do that? ’, ‘I don’t know. ’); } </script> This ends the function. This displays the three dialog boxes. 105 copyright Penny Mc. Intire, 2007

Example 1: A First Script • Not all Java. Script statements are required to

Example 1: A First Script • Not all Java. Script statements are required to end with a semi-colon (; ), but always do it anyway – it’s good programming practice and avoids confusion. • Note the escape character, “”, embedded in the text – just like C: alert(‘I've fallen and I can't get up!’); 106 copyright Penny Mc. Intire, 2007

alert, confirm, and prompt • alert, confirm, and prompt are special user-interface mechanisms defined

alert, confirm, and prompt • alert, confirm, and prompt are special user-interface mechanisms defined in the DOM Window Object. 107 copyright Penny Mc. Intire, 2007

alert, confirm, and prompt – alert displays a message in a dialog box. alert(‘I've

alert, confirm, and prompt – alert displays a message in a dialog box. alert(‘I've fallen and I can't get up!’); Call to the alert() method. Quotes enclose the string parameter to be displayed. Parentheses enclose the parameter(s) passed to alert(). 108 copyright Penny Mc. Intire, 2007

alert, confirm, and prompt – confirm returns a boolean true or false. – Right

alert, confirm, and prompt – confirm returns a boolean true or false. – Right now, we aren’t doing anything with the returned value, but we could use it in a conditional statement like an “if” … if (confirm(‘Will you help me? ’)) do something nice… else do something nasty … 109 copyright Penny Mc. Intire, 2007

alert, confirm, and prompt – prompt is a dialog which contains a text field

alert, confirm, and prompt – prompt is a dialog which contains a text field used to retrieve user input and returns it. prompt(‘How will you do that? ’, ‘I don’t know. ’); • The first parameter, ‘How will you do that? ’, is the static message string to be displayed. • The second string, ‘I don’t know. ’, is the (optional) default value in the text field. • Again, we aren’t yet doing anything with the returned value, but it is the user-entered string. 110 copyright Penny Mc. Intire, 2007

alert, confirm, and prompt • You can’t do standard html (tag-based) formatting within alert,

alert, confirm, and prompt • You can’t do standard html (tag-based) formatting within alert, confirm, and prompt boxes; you are restricted to spaces, newlines, and punctuation characters. • So, this won’t work the way you might think: alert(“<EM>Hello there!</EM>”); 111 copyright Penny Mc. Intire, 2007

Example: A First Script • Now let’s look briefly at the Java. Script in

Example: A First Script • Now let’s look briefly at the Java. Script in the <body>… 112 copyright Penny Mc. Intire, 2007

<html><head><title>Fun with Java. Script, #1</title> <script language="Java. Script"> function my. First. Function() { alert(‘I've

<html><head><title>Fun with Java. Script, #1</title> <script language="Java. Script"> function my. First. Function() { alert(‘I've fallen and I can't get up!’); confirm(‘Will you help me? ’); prompt(‘How will you do that? ’, ‘I don’t know. ’); } </script> The </head> “onclick” event executes the function. <body> <h 1>This shows an alert box. </h 1> <form> <input type=“button" value="Click to try a JS Function” onclick="my. First. Function()"> </form> </body> </html>

Example: A First Script • Note that there aren’t any <script> tags here. •

Example: A First Script • Note that there aren’t any <script> tags here. • When an event handler like onclick is used, statements within the quotes are assumed to execute some Java. Script, most often to call a function. 114 copyright Penny Mc. Intire, 2007

Example: Introduction • Next, we’ll look at a more representative example of the topics

Example: Introduction • Next, we’ll look at a more representative example of the topics we have been discussing. /Java. Script. Examples/js 02. html 115 copyright Penny Mc. Intire, 2007

<html> <head> <title>Fun with Java. Script, #2</title> <script language = "Java. Script"> // This

<html> <head> <title>Fun with Java. Script, #2</title> <script language = "Java. Script"> // This script converts Irish pounds into American dollars. var exchange. Rate = 1. 25; var irish. Pounds = 150; var american. Dollars = exchange. Rate * irish. Pounds; </script> </head> var declarations This script in the head sets up hard -coded variables needed to convert Irish pounds to American dollars, but doesn’t display anything.

This script in the <body> displays the variables as well as the calculated value.

This script in the <body> displays the variables as well as the calculated value. <body> <h 1>This screen converts Irish pounds to American dollars</h 1> <script language = "Java. Script"> document. writeln(‘With an exchange rate of ’ + exchange. Rate + ‘, ’); document. writeln(irish. Pounds + ‘ Irish pounds are equal to ’); document. writeln(american. Dollars + ‘ American dollars. ’); </script> <p>That's all, folks!</p> </body> </html> Display some text at the end of your document while you are debugging, then delete. Plus sign here means “concatenate”. . . document. writeln( ) writes whatever is between the parentheses.

Location of Java. Script • What Java. Script goes in the <head> of a

Location of Java. Script • What Java. Script goes in the <head> of a page and what goes in the <body>? • Most of your Java. Script, particularly variable and function definitions, should be contained in the <head>. – <head> elements are loaded before <body> elements, so variables (like exchange. Rate) initialized in the <head> are available to Java. Script located within the <body>. 118 copyright Penny Mc. Intire, 2007

Location of Java. Script – If you try to use a variable within a

Location of Java. Script – If you try to use a variable within a document. writeln() before it is defined, you'd get an “undefined” Java. Script error. • On the other hand, Java. Script that is used to generate the actual content of the page, like the writeln() commands, can be in the body, where content is actually generated. • Rule of thumb: if it concerns display on the page, it perhaps can go in the body. Otherwise, best if in the head. 119 copyright Penny Mc. Intire, 2007

Example 2 a: Moving Formatting to the <head> • Let’s look at another version

Example 2 a: Moving Formatting to the <head> • Let’s look at another version of this same script, this time formatting the displayed text in the <head>… 120 copyright Penny Mc. Intire, 2007

<html><head><title>Fun with Java. Script, #13</title> <script language = "Java. Script"> // This script converts

<html><head><title>Fun with Java. Script, #13</title> <script language = "Java. Script"> // This script converts Irish pounds into American dollars. var exchange. Rate = 1. 25; var irish. Pounds = 150; var american. Dollars = exchange. Rate * irish. Pounds; var my. Line = (‘With an exchange rate of ’ + exchange. Rate + ‘, ’); my. Line += (irish. Pounds + ‘ Irish pounds are equal to ’); my. Line += (american. Dollars + ‘ American dollars. ’); </script></head> This uses += to concatenate all of the displayed text into one variable.

<body> <h 1>This screen converts Irish pounds to American dollars</h 1> <script language =

<body> <h 1>This screen converts Irish pounds to American dollars</h 1> <script language = "Java. Script"> document. writeln(my. Line); </script> <p>That's all, folks!</p> </body> </html> Now, a single document. writeln() is used, which is more efficient.

Example: Prompt for Variables • Let’s look at another example of Java. Script, this

Example: Prompt for Variables • Let’s look at another example of Java. Script, this time using the prompt to get the variables, and storing the displayed lines as variables. . . js 03. html 123 copyright Penny Mc. Intire, 2007

<html><head><title>Fun with Java. Script, #3</title> <script language = "Java. Script"> var exchange. Rate =

<html><head><title>Fun with Java. Script, #3</title> <script language = "Java. Script"> var exchange. Rate = prompt('Enter exchange rate', '1. 25'); var irish. Pounds = prompt('Enter Irish pounds', '1'); var american. Dollars = exchange. Rate * irish. Pounds; var my. Line = 'With an exchange rate of ' + exchange. Rate + ', ' my. Line += irish. Pounds + ' Irish pounds are equal to ' my. Line += american. Dollars + ' American dollars. '</script> </head> Now, we use the prompt to get the two necessary variables, each with a default value. <body> <h 1>This screen converts Irish pounds to American dollars</h 1> <script language="Java. Script"> document. writeln(my. Line); </script> <p>That's all, folks!</p> </body></html>

Creating User-defined Functions • Review of functions… – A function is user-defined. – A

Creating User-defined Functions • Review of functions… – A function is user-defined. – A function is defined once and can then be invoked many times. – It can be invoked by an event handler or by a statement elsewhere in a script. – It can be passed parameters/arguments and can return values, although it doesn’t have to do so. 125 copyright Penny Mc. Intire, 2007

Creating User-defined Functions • Format: function name(parms) { Javascript code } The differences here

Creating User-defined Functions • Format: function name(parms) { Javascript code } The differences here are cosmetic only; use whichever format you prefer. 126 copyright Penny Mc. Intire, 2007

Creating User-defined Functions • To invoke a function that returns a value, simply use

Creating User-defined Functions • To invoke a function that returns a value, simply use the function call like any other expression. • That is, plug it in where you want the return value to be placed. . . 127 copyright Penny Mc. Intire, 2007

Creating User-defined Functions • Example: function addtwo(num 1 b, num 2 b) { return

Creating User-defined Functions • Example: function addtwo(num 1 b, num 2 b) { return num 1 b + num 2 b }. . . new. Value = addtwo(num 1 a, num 2 a) 128 copyright Penny Mc. Intire, 2007

Creating User-defined Functions • Example: function addtwo(num 1 b, num 2 b) { return

Creating User-defined Functions • Example: function addtwo(num 1 b, num 2 b) { return num 1 b + num 2 b } Parameters are defined automatically; they don’t need var statements. . new. Value = addtwo(num 1 a, num 2 a) 129 copyright Penny Mc. Intire, 2007

Creating User-defined Functions • Positional parameters: if leaving a parameter out, hold its place

Creating User-defined Functions • Positional parameters: if leaving a parameter out, hold its place with ‘, ’ 130 copyright Penny Mc. Intire, 2007

Event Handlers • Remember how we said that Java. Script is event-driven? • An

Event Handlers • Remember how we said that Java. Script is event-driven? • An event handler is invoked by the browser when an event occurs, like a user clicking on a button. • Event handlers are defined as attributes of their objects; for instance, a button click handler would be defined as an attribute of that button object. 131 copyright Penny Mc. Intire, 2007

Event Handlers • To define the event handler, you set it as an attribute

Event Handlers • To define the event handler, you set it as an attribute of the object. <input type = “button” name = “mybutton” value = “Click if Student” onclick = “my. Function()” > • Here, the event handler invokes the Java. Script function named my. Function. 132 copyright Penny Mc. Intire, 2007

Example: on. Click and on. Mouseover • Note that the event handlers used within

Example: on. Click and on. Mouseover • Note that the event handlers used within the HTML are considered HTML, not Java. Script, and as such, are not case sensitive. So on. Click, onclick, and ONCLICK are identical. • Let’s look at on. Click and on. Mouse. Over events. . . Js 06. html (test both on. Click and on. Mouse. Over) 133 copyright Penny Mc. Intire, 2007

<html><head><title>Fun with Java. Script, #6</title></head> “#” means a null link. <body <h 1>Link Events,

<html><head><title>Fun with Java. Script, #6</title></head> “#” means a null link. <body <h 1>Link Events, on. Click and on. Mouse. Over</h 1> <p> on. Click event triggers the alert. <a href = "#" on. Click = "alert('Hey! That hurt! Cut it out!'); ” > Click here!</a></p> <p> Everything else in the <a href = "#" <a> tag is the same. on. Mouse. Over = "alert('That was special!'); ” > Mouse over me!</a></p> <p>That's all, folks!</p> </body> </html> Note there are no <script> tags – anything that appears in the quotes of event handlers like on. Click or on. Mouse. Over is automatically interpreted as Java. Script.

Example: on. Click and on. Mouseover • These on. Click and on. Mouse. Over

Example: on. Click and on. Mouseover • These on. Click and on. Mouse. Over methods state, "When someone clicks/moves the mouse over this link, run the little bit of Java. Script between my quotes. " • Reading on events, DHTML, Chapter 3. 135 copyright Penny Mc. Intire, 2007

Example: Image Swaps • One of the most commonly used features of Java. Script

Example: Image Swaps • One of the most commonly used features of Java. Script is the ability to change images on a mouseover. • So, let’s look at the wonderful land of image swaps. js 07. html 136 copyright Penny Mc. Intire, 2007

This statement says, “on. Mouse. Over, find the. Image <html><head><title>Fun with Java. Script, #7</title></head>

This statement says, “on. Mouse. Over, find the. Image <html><head><title>Fun with Java. Script, #7</title></head> and change its src to “image. Swap 2”. This is changing the DOM on the fly <body> <h 1>Image Swapping</h 1> <a href="#" on. Mouse. Over = "document. the. Image. src = 'image. Swap 2. gif'; ” on. Mouse. Out = "document. the. Image. src = 'image. Swap 1. gif'; ” > <img NAME="the. Image" src="image. Swap 1. gif"> </a> <p>That's all, folks!</p> This statement says, “on. Mouse. Out, go back to the original image. ” </body> </html> A standard <img> tag, embedded in an anchor tag, except this one has been given a name, “the. Image”.

Example: Image Swaps • On image swapping, it’s best if the two images are

Example: Image Swaps • On image swapping, it’s best if the two images are the same size. – The theory is, if they’re not, the replacement image will get squashed or stretched to fit the original's size. – That’s not the way it worked in my example, in IE, as you saw…Why not? 138 copyright Penny Mc. Intire, 2007

Example: Image Swaps #2 • A variation on this, using on. Mouse. Down and

Example: Image Swaps #2 • A variation on this, using on. Mouse. Down and on. Mouse. Up, and using a remote image (the trigger changes an image elsewhere on the page). js 08. html 139 copyright Penny Mc. Intire, 2007

<html><head><title>Fun with Java. Script, #8</title></head> <body> <h 1>Image Swapping</h 1> <img NAME="the. Image" src='data:image/svg+xml,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22%20viewBox=%220%200%20415%20289%22%3E%3C/svg%3E' data-src="image.

<html><head><title>Fun with Java. Script, #8</title></head> <body> <h 1>Image Swapping</h 1> <img NAME="the. Image" src="image. Swap 1. gif" > <a href="#" on. Mouse. Down = "document. the. Image. src='image. Swap 2. gif'; ” on. Mouse. Up = "document. the. Image. src='image. Swap 1. gif'; "> Click here to change the image. </a> <p>That's all, folks!</p> </body> </html> Here, the anchor tag contains a text anchor, not the image to be swapped; the image that is being changed is somewhere else on the page. That’s a remote trigger.

Event Handlers • Which is correct? – on. Mouse. Over – onmouseover – ONMOUSEOVER

Event Handlers • Which is correct? – on. Mouse. Over – onmouseover – ONMOUSEOVER • When used in HTML, like we have just seen, it doesn’t matter – they are all the same thing because HTML is not casesensitive. • Event references Chapter 3 DHTML, but 141 add “on” prefix to the event for HTML. copyright Penny Mc. Intire, 2007

Event Handlers • Java. Script, on the other hand, is case sensitive. • So,

Event Handlers • Java. Script, on the other hand, is case sensitive. • So, when the event handler is used as a property of an object in Java. Script, it must be all lower case to be compatible across platforms. • Example: document. my. Button. onclick 142 copyright Penny Mc. Intire, 2007

Event Handlers • Common events (others in DHTML): – on. Change: An element has

Event Handlers • Common events (others in DHTML): – on. Change: An element has lost focus (i. e. , no longer selected) and the content of the element has changed since it gained focus. – on. Click: the user has pressed and released a mouse button (or keyboard equivalent) on an element. – on. Focus: an element has received the input focus; i. e. , it is selected. 143 copyright Penny Mc. Intire, 2007

Event Handlers – on. Key. Down: the user pressed a keyboard character key. –

Event Handlers – on. Key. Down: the user pressed a keyboard character key. – on. Key. Press: the user has pressed and released a keyboard character key. – on. Key. Up: the user has released a keyboard character key. – on. Load: a document has completed downloading into the browser. • Most commonly placed in the <body>. 144 copyright Penny Mc. Intire, 2007

Event Handlers – on. Mouse. Down: the user has pressed (but not released) a

Event Handlers – on. Mouse. Down: the user has pressed (but not released) a mouse button. – On. Mouse. Over: the user has rolled the mouse over an element. – on. Mouse. Out: the user has rolled the mouse out of an element. – on. Mouse. Up: the user has released the mouse button. – on. Submit: a form is about to be submitted. 145 copyright Penny Mc. Intire, 2007

Event Handlers • Variables used by the function that is invoked must have already

Event Handlers • Variables used by the function that is invoked must have already been defined when the user clicks. – This reinforces the argument for defining all functions within the <head> section, since this section is always completely parsed before the <body> section. – In a case where the user might click on something before all the necessary data is available (say, clicking “submit” when all data hasn’t yet been entered), check the data to make sure it isn’t null before using. 146 copyright Penny Mc. Intire, 2007

Example: Text Formatting • Let’s look at some formatting methods in Java. Script. .

Example: Text Formatting • Let’s look at some formatting methods in Java. Script. . . js 04. html 147 copyright Penny Mc. Intire, 2007

<html><head><title>Fun with Java. Script, #4</title> <script language = "Java. Script"> These use object var

<html><head><title>Fun with Java. Script, #4</title> <script language = "Java. Script"> These use object var line. Plain = ‘<p>Hello everyone. </p>’; methods to apply var line. Bold = line. Plain. bold(); var line. Green = line. Plain. fontcolor(‘green’); formatting to the var line. Big = line. Plain. fontsize(‘ 6’); objects. var line. Upper. Case = line. Plain. to. Upper. Case(); </script> </head> <body> <script language = "Java. Script"> document. writeln(line. Plain) document. writeln(line. Bold) document. writeln(line. Green) document. writeln(line. Big) document. writeln(line. Upper. Case) </script> <p>That's all, folks!</p></body></html> This says, “Take the line. Plain variable and convert it to upper case.

Hiding Java. Script from Brain-dead Browsers • Ancient browsers don't understand the <script> tag.

Hiding Java. Script from Brain-dead Browsers • Ancient browsers don't understand the <script> tag. • These browsers treat your Java. Script just like HTML, which means that all they can do is display the Java. Script itself like text. • We use a cheap trick that hides the Java. Script in those cases; enclose the script within the following html comments. . . 149 copyright Penny Mc. Intire, 2007

Hiding Java. Script from Brain-dead Browsers <script language="Java. Script"> JS comment <!-- hide from

Hiding Java. Script from Brain-dead Browsers <script language="Java. Script"> JS comment <!-- hide from old browsers your Java. Script goes here. . . HTML comment // stop hiding here --> JS comment </script> • This works because <!-- comments here --> – is a multi-line comment in html. – a single-line comment in Java. Script. 150 copyright Penny Mc. Intire, 2007

Hiding Java. Script from Brain-dead Browsers • Java. Script recognizes the beginning HTML tag,

Hiding Java. Script from Brain-dead Browsers • Java. Script recognizes the beginning HTML tag, but it doesn’t know what to do with the ending part of the tag, so you have to put // at the beginning of that line. • It's weird and tricky, but it works – you can copy and paste it into your Java. Script, for visitors with JS turned off. • I don’t use in class examples. 151 copyright Penny Mc. Intire, 2007

Using Java. Script • Recap: we have looked at the most common ways to

Using Java. Script • Recap: we have looked at the most common ways to use Java. Script: – Java. Script in the head, which resides within <script> and </script> tags. • Functions aren’t executed until invoked by a call from elsewhere in the document. – Java. Script function or command invoked by an event handler (on. Click, on. Mouse. Over, etc. ) within an HTML tag. 152 copyright Penny Mc. Intire, 2007

Using Java. Script – Java. Script in-line in the <body>, within <script> tags, as

Using Java. Script – Java. Script in-line in the <body>, within <script> tags, as when we had the document. writeln() methods in the body of our earlier examples. 153 copyright Penny Mc. Intire, 2007

Example: Debugging Java. Script • Let’s look at how we recognize and debug Java.

Example: Debugging Java. Script • Let’s look at how we recognize and debug Java. Script errors. . . js 02 error. html 154 copyright Penny Mc. Intire, 2007

Debugging Java. Script • Notice that if there is an error, IE displays a

Debugging Java. Script • Notice that if there is an error, IE displays a tiny little symbol in the bottom left corner. – Double click to get to the error messages. – Occasionally, the error message is even somewhat descriptive. – Some browsers count the line number from the beginning <script> tag for the script that is in error. (Gee, thanks. ) 155 copyright Penny Mc. Intire, 2007

Debugging Java. Script • The line number may be off by several lines. –

Debugging Java. Script • The line number may be off by several lines. – Examples: • A missing } might not be detected and flagged until several lines after it should have occurred. • The <script> line might be flagged when the error is further down in the script. 156 copyright Penny Mc. Intire, 2007

Debugging Java. Script • In IE, if there are multiple messages, the first one

Debugging Java. Script • In IE, if there are multiple messages, the first one will be at the top even though the last message is the one that has focus when the window comes up. – Just scroll up to the first message. 157 copyright Penny Mc. Intire, 2007

Debugging Java. Script • Java. Script is harder to debug than compiled programs, like

Debugging Java. Script • Java. Script is harder to debug than compiled programs, like COBOL or C programs. • Syntax errors aren’t flagged with descriptive error messages. • The best you will get is the line number of the error, and, as we have seen, even that can be misleading. 158 copyright Penny Mc. Intire, 2007

Debugging Java. Script • Comment out part of the code to see what works.

Debugging Java. Script • Comment out part of the code to see what works. – If you are working from an error message, comment that line out and reload. – Keep “commenting out” your way backward and/or forward until the problem goes away – you’ve found your bad line. • Insert alert boxes as debugging aids, to trace the execution of the code and to display values for variables. 159 copyright Penny Mc. Intire, 2007

Common Java. Script Errors • Forgetting the semi-colon at the end of a line

Common Java. Script Errors • Forgetting the semi-colon at the end of a line (though this is often ok). • Forgetting () on a function call. • Forgetting that Java. Script is casesensitive. 160 copyright Penny Mc. Intire, 2007

Common Java. Script Errors • Something is undefined: – Using a variable that hasn’t

Common Java. Script Errors • Something is undefined: – Using a variable that hasn’t yet had a value assigned to it. – There is a non-numeric value in an item that is treated as a number. – A function has not been defined, which might very well be the fault of a spelling error or a missing end brace in the function just before the “undefined” function. 161 copyright Penny Mc. Intire, 2007

Common Java. Script Errors • Unterminated string literal. – Forgetting an ending quote. –

Common Java. Script Errors • Unterminated string literal. – Forgetting an ending quote. – Nesting more than two levels deep, with single and double quotes. • Technically legal, but sometimes doesn’t work. • Break the string up instead. • Missing } after function body. – May actually refer to a missing } much earlier that wasn’t detected until the end of the indicated function. 162 copyright Penny Mc. Intire, 2007

Common Java. Script Errors • Something is not a number. – Variable contains a

Common Java. Script Errors • Something is not a number. – Variable contains a string or no value at all. – If it doesn’t identify the variable in error, it usually means the message is completely bogus. • Java. Script has a vague “feeling” that something’s wrong, but doesn’t know it exactly what it is. 163 copyright Penny Mc. Intire, 2007

Common Java. Script Errors • Something has no property named. – Usually caused by

Common Java. Script Errors • Something has no property named. – Usually caused by an improper DOM reference, perhaps forgetting to use a subscript for an item that is a member of an array. • Test for equality (==) mistyped as assignment (=). 164 copyright Penny Mc. Intire, 2007

Common Java. Script Errors • “Lengthy Java. Script is still running. Continue? ” –

Common Java. Script Errors • “Lengthy Java. Script is still running. Continue? ” – Infinite loop. • Syntax error. – Duh. • Too many Java. Script errors. – My personal favorite. – Usually the result of a bug within a loop. 165 copyright Penny Mc. Intire, 2007

Common Java. Script Errors • Unpaired HTML tags. • Putting scripts inside tables can

Common Java. Script Errors • Unpaired HTML tags. • Putting scripts inside tables can cause some peculiar bugs. • Reload should reload the page, but doesn’t always; use Shift-Reload to force a reload. 166 copyright Penny Mc. Intire, 2007

Java. Script Programming Hints • Get the HTML working before adding in any Java.

Java. Script Programming Hints • Get the HTML working before adding in any Java. Script, or… • Test Java. Script functions within a skeleton HTML file to see if they work before dropping them into a complex page. • Either way, add Java. Script in chunks, making sure each chunk works before adding the next chunk. 167 copyright Penny Mc. Intire, 2007