JavaScript Syntax 1 copyright Penny McIntire, 2007 JavaScript Introduction • As we saw, JavaScript 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 McIntire, 2007 JavaScript 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 JavaScript file much like an external CSS file, if it’s to be used by more than one page. 3 copyright Penny McIntire, 2007 JavaScript 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 McIntire, 2007 JavaScript Introduction • Since JavaScript is embedded as plain text in an html file, you can use Editpad (under Utilities in my public directory) to enter JavaScript into your HTML files or you can do it directly in Dreamweaver. • Use “View Source” frequently on the web; the best way to learn JavaScript is to look at scripts other people have written. 5 copyright Penny McIntire, 2007 JavaScript Introduction • One of the coolest features of JavaScript 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 McIntire, 2007 JavaScript Syntax • JavaScript syntax is easy – using JavaScript is not necessarily all that easy. • Although you'll learn much of the syntax of JavaScript 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 McIntire, 2007 JavaScript Introduction • JavaScript 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. – JavaScript debugger tutorial http://www.informit.com/articles/article.as 8 px?p=29739 debugger. copyright Penny McIntire, 2007 JavaScript Syntax • First, let’s look at some JavaScript... (js01.html) 9 copyright Penny McIntire, 2007 <html><head><title>fun with javascript, #1</title> <script language="JavaScript"> function myFirstFunction() { 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> <h1>This shows an alert, a confirm, and a prompt.</h1> <form> <input type=“submit" value="Click to try a JS Function” onclick="myFirstFunction()"> The “onclick” </form> event executes the </body> function. </html> Similarities to C syntax • If you know C/C++ (and all of you folks do), you know most of the JavaScript 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 McIntire, 2007 Expressions and Operators • An expression is merely a phrase that the JavaScript interpreter evaluates to produce a value. • Examples of expressions: – a variable name like myNumber – string literal ‘Hello World’ – numeric literal 89.1 – Boolean literal true 12 copyright Penny McIntire, 2007 Expressions and Operators • An operator is a symbol that is used to combine two or more expressions. • Mathematical operators… 13 copyright Penny McIntire, 2007 Expressions and Operators +, -, *, / ++ -% +=, -= as we have seen, but be careful with + (can be concatenation). increment by one, prefix and postfix ( ++myNum or myNum++ ) decrement by one, prefix and postfix ( - - myNum or myNum - - ) modulo; finds remainder (10 % 7 would be 3) add-by-value, subtract-by-value 14 copyright Penny McIntire, 2007 Expressions and Operators • Careful with the “+” symbol – When used between two variables that JavaScript 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 JavaScript data types. 15 copyright Penny McIntire, 2007 Expressions and Operators • Let’s look at the other expressions and operators... 16 copyright Penny McIntire, 2007 Expressions and Operators == != < <= > >= ! && || new 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 create a new object 17 copyright Penny McIntire, 2007 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 McIntire, 2007 Expressions and Operators • Comparisons: – Just like the Java language, JavaScript 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 McIntire, 2007 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 McIntire, 2007 Expressions and Operators • Rule of thumb: use parentheses and/or convert variables! • And another thing…JavaScript statements end with a semi-colon. Not always required, but good programming practice. 21 copyright Penny McIntire, 2007 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: myArray = new Array (2,18, 21, 5) myObject = new Object ( ) Puts these values in the array. 22 copyright Penny McIntire, 2007 Control Structures • The basic form of an if-then statement: if (some condition) { do something; do something; } else { do something else; } 23 copyright Penny McIntire, 2007 Control Structures • Compound conditions use && (and) and || (or): if ((some condition) && (another condition)) { do something; do something; } else { do something else; } 24 copyright Penny McIntire, 2007 Control Structures • else if – used to implement a “case” structure using multiple variables; that is, more than two different conditions. 25 copyright Penny McIntire, 2007 if ( inputNum = = ' ') { alert (' Please enter a valid number between 0 and 100.'); } else if ( inputNum <= 0 ) { alert (' Negative numbers and 0 are not allowed. '); } else if ( inputNum > 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 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 McIntire, 2007 switch ( inputNum ) { 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, except JavaScript: – 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 JavaScript is loosely-typed (more later). 29 copyright Penny McIntire, 2007 Control Structures • while statement myCount = 1; while ( myCount <= 10 ) { …do something… myCount = myCount +1 } 30 copyright Penny McIntire, 2007 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 McIntire, 2007 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 McIntire, 2007 Control Structures for( myCtr = 0 ; myCtr < 10 ; myCtr++ ) { …do something… } Will loop 10 times. 33 copyright Penny McIntire, 2007 Comments • Comments – same as in C – // This is a single-line comment – JavaScript here… //comment here – /* This is a multiple-line comment within a script.*/ 34 copyright Penny McIntire, 2007 JavaScript Variables 35 copyright Penny McIntire, 2007 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: JavaScript 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 McIntire, 2007 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 McIntire, 2007 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 McIntire, 2007 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 McIntire, 2007 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 JavaScript have function-wide scope, not block scope. 40 copyright Penny McIntire, 2007 Variable Declaration • To declare a variable explicitly, use var. var myNumber; var variableName1, variableName2; • These declare the variables but don’t assign values, which means they will be undefined until you assign values to them. 41 copyright Penny McIntire, 2007 Variable Declaration • You can also assign a value when making a declaration: var variableName1 = 16, variableName2 = ‘Error in input’, variableName3 = 285.03; 42 copyright Penny McIntire, 2007 Variable Declaration • Here we see some basic math used to initialize a variable: var americanDollars = exchangeRate * irishPounds; • 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 McIntire, 2007 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 McIntire, 2007 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 McIntire, 2007 Data Typing • JavaScript 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 McIntire, 2007 Data Typing • When you do so, as an intermediate step, JavaScript 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 McIntire, 2007 var • So, a given var can “morph” into all myString kinds of data. (Seems so wrong, Now but holds a get used to it!) numeric 12. var myString = ‘Hi there.’; myString = 3 * 4; OR var Now myString holds a numeric 6. myString = ‘3’; myString = myString * 2 48 copyright Penny McIntire, 2007 JavaScript Data Types • Data types in JavaScript – numbers – strings – boolean 49 copyright Penny McIntire, 2007 Conversion Rules • As I said earlier, JavaScript converts a var to the appropriate data type based on how it’s being used. • To do so, JavaScript evaluates the expression to determine the output data type. • Big caution here: JavaScript 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 McIntire, 2007 Conversion Rules • For the + sign: – If both variables are numbers, standard addition is performed. • Examples: – 16 + 2 evaluates to 18 – If myField contains 23, myField + 8 evaluates to 31 51 copyright Penny McIntire, 2007 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 myField contains “23”, myField + 8 evaluates to “238” 52 copyright Penny McIntire, 2007 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 McIntire, 2007 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 McIntire, 2007 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 McIntire, 2007 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 McIntire, 2007 Conversion Rules • Rule of thumb: keep track of your own data types, and convert them yourself when necessary. 57 copyright Penny McIntire, 2007 Primitive Data Types • Again, there are three primitive data types in JavaScript: 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 McIntire, 2007 Numbers • Number objects do not distinguish between integers and floating-point (decimal) numbers. • All numbers are treated as floatingpoint when necessary. 59 copyright Penny McIntire, 2007 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 McIntire, 2007 Numbers • Special, abstract value NaN 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 NaN – it isn’t even equal to itself! – Instead, use the function isNaN() and test for true. 61 copyright Penny McIntire, 2007 Numbers • To declare a var as an official Number object, var myNewNumber = new Number(42); 62 copyright Penny McIntire, 2007 Numbers • Why bother, when JavaScript 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 McIntire, 2007 String Syntax • For representing and manipulating text. • To declare a var as a String object, var myNewString = new String(“the string”); – Enclose the literal in matching pairs of single or double quotes. – Because JavaScript is embedded within html (which commonly uses double quotes), many experts believe it’s good practice to use single quotes for JavaScript. 64 copyright Penny McIntire, 2007 String Syntax – I did that for these lectures, but I don’t necessarily agree. – I usually type double quotes outside (whether html or JavaScript), then start alternating as I hit inside quotes. 65 copyright Penny McIntire, 2007 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 JavaScript or that can’t be represented in any other way, such as the apostrophe… 66 copyright Penny McIntire, 2007 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 McIntire, 2007 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 McIntire, 2007 Strings • Object contains multiple methods for doing common string manipulations, such as: – charAt(index) – indexOf(“char”) – substr(start, length) – search(regExp) 69 copyright Penny McIntire, 2007 String Syntax • To get the length of a string, use the length property: This is the variable for which we need the length. myStringLength = myBirthday.length This variable will hold the length after this command executes. This property of the myBirthday object holds the length. 70 copyright Penny McIntire, 2007 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. myString += ‘add this to the end’; myString +=‘ and then add this on, too”; 71 copyright Penny McIntire, 2007 Boolean • As with other languages, boolean can contain only two values, true and false. • Typically boolean values are used with a control statement such as an if. if (num1 == 16) x = x + 1; else y = y + 1; Has a boolean value of true or false. 72 copyright Penny McIntire, 2007 Boolean • To declare a var as a Boolean object, var myNewBoolean = 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 McIntire, 2007 Object Conversion • As we have now stated repeatedly, JavaScript 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 McIntire, 2007 Object Conversion to Number • Use the parseInt() method to convert a String or Boolean to an integer (no rounding): – Example: var myResult = parseInt(myStringNumber,10) + 23 – This converts whatever was in myStringNumber to an integer before doing the addition. An integer in base 10, usually the default. 75 copyright Penny McIntire, 2007 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 myResult = parseInt(myStringNumber, 10) + 23 76 copyright Penny McIntire, 2007 Object Conversion to Number • Use the parseFloat() method to convert a String or Boolean to a floating point (decimal) number: – Example: var myResult = parseFloat(myStringNumber,10) + 23.1 – This converts whatever was in myStringNumber to a number with the appropriate decimal places. 77 copyright Penny McIntire, 2007 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 McIntire, 2007 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 NaN before attempting to use it as a number. 79 copyright Penny McIntire, 2007 Object Conversion to String • To convert a Number to a String: – Concatenate it with an empty string: ...(myNum + ‘ ’ )... – Or use the toString() method of the Number object. 80 copyright Penny McIntire, 2007 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 McIntire, 2007 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 JavaScript 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 McIntire, 2007 Array Syntax • Use square brackets to enclose the index: – myArray [ 2 ] gets the third member. – myArray [ myIndex ] uses the value of myIndex to index the array. 83 copyright Penny McIntire, 2007 Array Syntax • Creating arrays var myVariable = 48 ; var myArray = new Array( ); myArray[0] = ‘This is my array’; myArray[1] = 86.35; myArray[2] = false; This is my array myArray[3] = myVariable; 86.35 false 48 84 copyright Penny McIntire, 2007 Array Syntax • The following gives the same results as previous example: var myArray = new Array(‘This is my array’, 86.35, false, myvariable) – Can leave one or more elements undefined by simply omitting values between commas var myArray = (‘This is my array’, 86.35, , myvariable) undefined. 85 copyright Penny McIntire, 2007 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 McIntire, 2007 Array Syntax • Can also simulate a multi-dimensional array with an array of arrays: myArray [index1] [index2] Complicated. • To add another element to an array: myArray[myArray.length] = “whatever” length property: if currently 4 entries, then this will add a 5th entry. 87 copyright Penny McIntire, 2007 Math Object • Another useful predefined object is the Math object, which contains a large library of commonly-used mathematical functions. Must be capitalized. • Examples: num1 num1 num1 num1 = = = = Math.sqrt(num2) Math.ceil(num2) Math.floor(num2) Math.round(num2) square root rounds num2 up rounds num2 down rounds by rule • For more math functions, see DHTML. 88 copyright Penny McIntire, 2007 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(irishPounds); – concatenated items (‘+’). document.writeln(americanDollars + ‘ American dollars.’); 89 copyright Penny McIntire, 2007 innerHTML • Allows you to access and manipulate the HTML inside of an HTML container. var x=document.getElementById("myHeader"); alert(x.innerHTML); … <h1 id="myHeader">Click me!</h1> • The alert will display "Click me!" 90 copyright Penny McIntire, 2007 document.writeln() • Let’s look at how this actually writes to the page from each line… 91 copyright Penny McIntire, 2007 document.writeln(‘With an exchange rate of ’ + exchangeRate + ‘, <br>’); With an exchange rate of 1.25 , document.writeln(irishPounds + ‘ Irish pounds are equal to <br>’); 150 Irish pounds are equal to document.writeln(americanDollars + ‘ American dollars.’); 187.5 American dollars. Null in JavaScript • 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 JavaScript is not zero; this is different from null in the C language. 93 copyright Penny McIntire, 2007 Undefined in JavaScript • 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 McIntire, 2007 Undefined in JavaScript • In older versions of JavaScript, there was no undefined operator. – Instead, you would test for null (not really the same, but they evaluate as the same). • Newer versions of JavaScript 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 McIntire, 2007 Embedding JavaScript in HTML Documents • JavaScript 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="JavaScript" src = "scriptNameAndPath.js"> </script> 96 copyright Penny McIntire, 2007 Embedding JavaScript in HTML Documents • The external file is identical to a normal JavaScript script, except no <script>...</script>. • The file loads when the <head> loads, so – JavaScript 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 McIntire, 2007 Embedding JavaScript in HTML Documents – In the <head> • Embed within <script language="JavaScript"> ... <script> • JavaScript 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 McIntire, 2007 Embedding JavaScript 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="JavaScript"> ... <script> – Used primarily to write “text” out to the page. – Executed as they are encountered in the HTML code. 99 copyright Penny McIntire, 2007 Embedding JavaScript in HTML Documents • <script language="JavaScript"> – Specifying language="JavaScript" 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 McIntire, 2007 Embedding JavaScript in HTML Documents – Can also include the JavaScript version number with it, <script language="JavaScript1.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 McIntire, 2007 Example 1: A First Script • Let’s look at our first example of JavaScript... /JavaScriptExamples/js01.html 102 copyright Penny McIntire, 2007 <html><head><title>Fun with JavaScript, #1</title> <script language="JavaScript"> This defines function myFirstFunction() 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> <h1>This shows an alert box.</h1> <form> <input type=“button" value="Click to try a JS Function” onclick="myFirstFunction()"> </form> </body> </html> Example 1: A First Script • Let’s look more closely at the function defined in the <head>… 104 copyright Penny McIntire, 2007 Example 1: A First Script <script language="JavaScript"> // This function sequentially displays three dialog boxes. This starts the function myFirstFunction() 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 displays the three dialog boxes. This ends the function. 105 copyright Penny McIntire, 2007 Example 1: A First Script • Not all JavaScript 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 McIntire, 2007 alert, confirm, and prompt • alert, confirm, and prompt are special user-interface mechanisms defined in the DOM Window Object. 107 copyright Penny McIntire, 2007 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 McIntire, 2007 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 McIntire, 2007 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 McIntire, 2007 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 McIntire, 2007 Example: A First Script • Now let’s look briefly at the JavaScript in the <body>… 112 copyright Penny McIntire, 2007 <html><head><title>Fun with JavaScript, #1</title> <script language="JavaScript"> function myFirstFunction() { 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 “onclick” </head> event executes the function. <body> <h1>This shows an alert box.</h1> <form> <input type=“button" value="Click to try a JS Function” onclick="myFirstFunction()"> </form> </body> </html> 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 JavaScript, most often to call a function. 114 copyright Penny McIntire, 2007 Example: Introduction • Next, we’ll look at a more representative example of the topics we have been discussing. /JavaScriptExamples/js02.html 115 copyright Penny McIntire, 2007 <html> <head> <title>Fun with JavaScript, #2</title> <script language = "JavaScript"> // This script converts Irish pounds into American dollars. var exchangeRate = 1.25; var irishPounds = 150; var americanDollars = exchangeRate * irishPounds; </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. <body> <h1>This screen converts Irish pounds to American dollars</h1> <script language = "JavaScript"> document.writeln(‘With an exchange rate of ’ + exchangeRate + ‘, <br>’); document.writeln(irishPounds + ‘ Irish pounds are equal to <br>’); document.writeln(americanDollars + ‘ 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 JavaScript • What JavaScript goes in the <head> of a page and what goes in the <body>? • Most of your JavaScript, particularly variable and function definitions, should be contained in the <head>. – <head> elements are loaded before <body> elements, so variables (like exchangeRate) initialized in the <head> are available to JavaScript located within the <body>. 118 copyright Penny McIntire, 2007 Location of JavaScript – If you try to use a variable within a document.writeln() before it is defined, you'd get an “undefined” JavaScript error. • On the other hand, JavaScript 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 McIntire, 2007 Example 2a: 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 McIntire, 2007 <html><head><title>Fun with JavaScript, #13</title> <script language = "JavaScript"> // This script converts Irish pounds into American dollars. var exchangeRate = 1.25; var irishPounds = 150; var americanDollars = exchangeRate * irishPounds; var myLine = (‘With an exchange rate of ’ + exchangeRate + ‘, <br>’); myLine += (irishPounds + ‘ Irish pounds are equal to <br>’); myLine += (americanDollars + ‘ American dollars.’); </script></head> This uses += to concatenate all of the displayed text into one variable. <body> <h1>This screen converts Irish pounds to American dollars</h1> <script language = "JavaScript"> document.writeln(myLine); </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 JavaScript, this time using the prompt to get the variables, and storing the displayed lines as variables... js03.html 123 copyright Penny McIntire, 2007 <html><head><title>Fun with JavaScript, #3</title> <script language = "JavaScript"> var exchangeRate = prompt('Enter exchange rate', '1.25'); var irishPounds = prompt('Enter Irish pounds', '1'); var americanDollars = exchangeRate * irishPounds; var myLine = 'With an exchange rate of ' + exchangeRate + ',<br>' myLine += irishPounds + ' Irish pounds are equal to <br>' myLine += americanDollars + ' American dollars.'</script> </head> Now, we use the prompt to get the two necessary variables, each with a default value. <body> <h1>This screen converts Irish pounds to American dollars</h1> <script language="JavaScript"> document.writeln(myLine); </script> <p>That's all, folks!</p> </body></html> 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 McIntire, 2007 Creating User-defined Functions • Format: function name(parms) { Javascript code } function name(parms) { Javascript code } The differences here are cosmetic only; use whichever format you prefer. 126 copyright Penny McIntire, 2007 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 McIntire, 2007 Creating User-defined Functions • Example: function addtwo(num1b, num2b) { return num1b + num2b } ... newValue = addtwo(num1a, num2a) 128 copyright Penny McIntire, 2007 Creating User-defined Functions • Example: function addtwo(num1b, num2b) { return num1b + num2b } Parameters are defined automatically; they don’t need var statements. ... newValue = addtwo(num1a, num2a) 129 copyright Penny McIntire, 2007 Creating User-defined Functions • Positional parameters: if leaving a parameter out, hold its place with ‘,’ 130 copyright Penny McIntire, 2007 Event Handlers • Remember how we said that JavaScript 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 McIntire, 2007 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 = “myFunction()” > • Here, the event handler invokes the JavaScript function named myFunction. 132 copyright Penny McIntire, 2007 Example: onClick and onMouseover • Note that the event handlers used within the HTML are considered HTML, not JavaScript, and as such, are not case sensitive. So onClick, onclick, and ONCLICK are identical. • Let’s look at onClick and onMouseOver events... Js06.html (test both onClick and onMouseOver) 133 copyright Penny McIntire, 2007 <html><head><title>Fun with JavaScript, #6</title></head> “#” means a null link. <body <h1>Link Events, onClick and onMouseOver</h1> <p> onClick event triggers the alert. <a href = "#" onClick = "alert('Hey! That hurt! Cut it out!');” > Click here!</a></p> <p> Everything else in the <a href = "#" <a> tag is the same. onMouseOver = "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 onClick or onMouseOver is automatically interpreted as JavaScript. Example: onClick and onMouseover • These onClick and onMouseOver methods state, "When someone clicks/moves the mouse over this link, run the little bit of JavaScript between my quotes." • Reading on events, DHTML, Chapter 3. 135 copyright Penny McIntire, 2007 Example: Image Swaps • One of the most commonly used features of JavaScript is the ability to change images on a mouseover. • So, let’s look at the wonderful land of image swaps. js07.html 136 copyright Penny McIntire, 2007 This statement says, “onMouseOver, find theImage <html><head><title>Fun with JavaScript, #7</title></head> and change its src to “imageSwap2”. This is changing the DOM on the fly. <body> <h1>Image Swapping</h1> <a href="#" onMouseOver = "document.theImage.src = 'imageSwap2.gif';” onMouseOut = "document.theImage.src = 'imageSwap1.gif';” > <img NAME="theImage" src="imageSwap1.gif"> </a> <p>That's all, folks!</p> This statement says, “onMouseOut, 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, “theImage”. 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 McIntire, 2007 Example: Image Swaps #2 • A variation on this, using onMouseDown and onMouseUp, and using a remote image (the trigger changes an image elsewhere on the page). js08.html 139 copyright Penny McIntire, 2007 <html><head><title>Fun with JavaScript, #8</title></head> <body> <h1>Image Swapping</h1> <img NAME="theImage" src="imageSwap1.gif" ><br> <a href="#" onMouseDown = "document.theImage.src='imageSwap2.gif';” onMouseUp = "document.theImage.src='imageSwap1.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? – onMouseOver – 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 McIntire, 2007 Event Handlers • JavaScript, on the other hand, is case sensitive. • So, when the event handler is used as a property of an object in JavaScript, it must be all lower case to be compatible across platforms. • Example: document.myButton.onclick 142 copyright Penny McIntire, 2007 Event Handlers • Common events (others in DHTML): – onChange: An element has lost focus (i.e., no longer selected) and the content of the element has changed since it gained focus. – onClick: the user has pressed and released a mouse button (or keyboard equivalent) on an element. – onFocus: an element has received the input focus; i.e., it is selected. 143 copyright Penny McIntire, 2007 Event Handlers – onKeyDown: the user pressed a keyboard character key. – onKeyPress: the user has pressed and released a keyboard character key. – onKeyUp: the user has released a keyboard character key. – onLoad: a document has completed downloading into the browser. • Most commonly placed in the <body>. 144 copyright Penny McIntire, 2007 Event Handlers – onMouseDown: the user has pressed (but not released) a mouse button. – OnMouseOver: the user has rolled the mouse over an element. – onMouseOut: the user has rolled the mouse out of an element. – onMouseUp: the user has released the mouse button. – onSubmit: a form is about to be submitted. 145 copyright Penny McIntire, 2007 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 McIntire, 2007 Example: Text Formatting • Let’s look at some formatting methods in JavaScript... js04.html 147 copyright Penny McIntire, 2007 <html><head><title>Fun with JavaScript, #4</title> <script language = "JavaScript"> These use object var linePlain = ‘<p>Hello everyone. </p>’; methods to apply var lineBold = linePlain.bold(); var lineGreen = linePlain.fontcolor(‘green’); formatting to the var lineBig = linePlain.fontsize(‘6’); objects. var lineUpperCase = linePlain.toUpperCase(); </script> </head> <body> <script language = "JavaScript"> document.writeln(linePlain) document.writeln(lineBold) document.writeln(lineGreen) document.writeln(lineBig) document.writeln(lineUpperCase) </script> <p>That's all, folks!</p></body></html> This says, “Take the linePlain variable and convert it to upper case. Hiding JavaScript from Brain-dead Browsers • Ancient browsers don't understand the <script> tag. • These browsers treat your JavaScript just like HTML, which means that all they can do is display the JavaScript itself like text. • We use a cheap trick that hides the JavaScript in those cases; enclose the script within the following html comments... 149 copyright Penny McIntire, 2007 Hiding JavaScript from Brain-dead Browsers <script language="JavaScript"> <!-- hide from old browsers JS comment your JavaScript 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 JavaScript. 150 copyright Penny McIntire, 2007 Hiding JavaScript from Brain-dead Browsers • JavaScript 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 JavaScript, for visitors with JS turned off. 151 • I don’t use in class examples. copyright Penny McIntire, 2007 Using JavaScript • Recap: we have looked at the most common ways to use JavaScript: – JavaScript in the head, which resides within <script> and </script> tags. • Functions aren’t executed until invoked by a call from elsewhere in the document. – JavaScript function or command invoked by an event handler (onClick, onMouseOver, etc.) within an HTML tag. 152 copyright Penny McIntire, 2007 Using JavaScript – JavaScript 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 McIntire, 2007 Example: Debugging JavaScript • Let’s look at how we recognize and debug JavaScript errors... js02error.html 154 copyright Penny McIntire, 2007 Debugging JavaScript • 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 McIntire, 2007 Debugging JavaScript • 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 McIntire, 2007 Debugging JavaScript • 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 McIntire, 2007 Debugging JavaScript • JavaScript 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 McIntire, 2007 Debugging JavaScript • 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 McIntire, 2007 Common JavaScript Errors • Forgetting the semi-colon at the end of a line (though this is often ok). • Forgetting () on a function call. • Forgetting that JavaScript is casesensitive. 160 copyright Penny McIntire, 2007 Common JavaScript 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 McIntire, 2007 Common JavaScript 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 McIntire, 2007 Common JavaScript 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. • JavaScript has a vague “feeling” that something’s wrong, but doesn’t know it exactly what it is. 163 copyright Penny McIntire, 2007 Common JavaScript 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 McIntire, 2007 Common JavaScript Errors • “Lengthy JavaScript is still running. Continue?” – Infinite loop. • Syntax error. – Duh. • Too many JavaScript errors. – My personal favorite. – Usually the result of a bug within a loop. 165 copyright Penny McIntire, 2007 Common JavaScript 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 McIntire, 2007 JavaScript Programming Hints • Get the HTML working before adding in any JavaScript, or… • Test JavaScript functions within a skeleton HTML file to see if they work before dropping them into a complex page. • Either way, add JavaScript in chunks, making sure each chunk works before adding the next chunk. 167 copyright Penny McIntire, 2007