114
Javascript Javascript Cyndi Hageman Cyndi Hageman

Javascript Cyndi Hageman. Javascript Basics Javascript is a scripting language, it is not compiled code. Javascript is a scripting language, it is not

Embed Size (px)

Citation preview

JavascriptJavascript

Cyndi HagemanCyndi Hageman

Javascript BasicsJavascript Basics Javascript is a scripting language, it is not compiled Javascript is a scripting language, it is not compiled

code. code. Javascript has object oriented capabilities. We create Javascript has object oriented capabilities. We create

or manipulate objects that have properties and or manipulate objects that have properties and methods.methods.

Javascript is embedded in HTML code and is Javascript is embedded in HTML code and is downloaded to the client’s machine when a web page downloaded to the client’s machine when a web page is loaded. The code runs on the client machine, not is loaded. The code runs on the client machine, not the web server.the web server.

Javascript will help make your web pages dynamic – Javascript will help make your web pages dynamic – you can interact with the client. Web pages alone are you can interact with the client. Web pages alone are static and designed only for display.static and designed only for display.

Javascript BasicsJavascript Basics

Case sensitive – an object named Case sensitive – an object named “txtFirstName” is different than “txtFirstName” is different than “txtFirstname” and different from “txtFirstname” and different from “txtfirstname”. There is no javascript function “txtfirstname”. There is no javascript function Alert() but there is a function alert().Alert() but there is a function alert().

Optional semi-colons – each javascript line of Optional semi-colons – each javascript line of code can be ended with a semi-colon. It is not code can be ended with a semi-colon. It is not required but recommended.required but recommended.

Javascript BasicsJavascript Basics

Comments – if you wish to add comments to your Comments – if you wish to add comments to your code you can add a one line comment by starting it code you can add a one line comment by starting it with //. If you wish to comment out a block of code, with //. If you wish to comment out a block of code, start with /* and end with */.start with /* and end with */.

Literals – data values that appear in your program. Literals – data values that appear in your program. 12 is the number 1212 is the number 12 ““Hello World” is a string of textHello World” is a string of text true is the boolean value truetrue is the boolean value true null is the absence of valuenull is the absence of value

Javascript BasicsJavascript Basics

Identifier – simply a name. You will need to Identifier – simply a name. You will need to add a name to several things in javascript – a add a name to several things in javascript – a variable, a function, a loop, etc. Names can be variable, a function, a loop, etc. Names can be anything you want with the exception of anything you want with the exception of reserved wordsreserved words

Reserved Words – words that have special Reserved Words – words that have special meaning in javascript and cannot be used as meaning in javascript and cannot be used as identifiers. Words listed on page 19 & 20 in identifiers. Words listed on page 19 & 20 in your book.your book.

Simple Dialog BoxesSimple Dialog Boxes

alert() – alerts the client of something. It blocks the alert() – alerts the client of something. It blocks the program from running until the user clicks OK. This program from running until the user clicks OK. This is the most commonly used dialog box and is used a is the most commonly used dialog box and is used a lot for debugging.lot for debugging.

prompt() – used to get a value from the client. The prompt() – used to get a value from the client. The client types in a value and clicks OK and the value is client types in a value and clicks OK and the value is returned to the program. This also blocks the program returned to the program. This also blocks the program from running until the user clicks OK. Two from running until the user clicks OK. Two parameters are passed to the prompt function. The parameters are passed to the prompt function. The first is the message to display. The second is a default first is the message to display. The second is a default value, which can be left blank.value, which can be left blank.

Simple Dialog BoxesSimple Dialog Boxes

confirm() – tells the user something and they confirm() – tells the user something and they need to respond by clicking OK or Cancel. need to respond by clicking OK or Cancel. You can capture what they clicked and You can capture what they clicked and proceed accordingly. This blocks the program proceed accordingly. This blocks the program from running until the client responds.from running until the client responds.

The alert() is used quite often. The confirm() The alert() is used quite often. The confirm() and prompt() are not used as often and are not and prompt() are not used as often and are not considered good design. There are better ways considered good design. There are better ways to get clients to enter information.to get clients to enter information.

Examples of Dialog BoxesExamples of Dialog Boxes

alert(“You must enter your zip code.”);alert(“You must enter your zip code.”); var getanswer;var getanswer;

getanswer=confirm(“Would you like to try getanswer=confirm(“Would you like to try again?”);again?”);

var val;var val;val = prompt(“Please enter a number:”,””);val = prompt(“Please enter a number:”,””);

VariablesVariables

A variable is a name associated with a value. A variable is a name associated with a value. The variable is said to store or contain a value.The variable is said to store or contain a value.

You declare the existence of a variable by You declare the existence of a variable by using they keyword var.using they keyword var.

var i;var i;

var val;var val;

var i, val;var i, val;

Variables and Data TypesVariables and Data Types

Javascript variables are untyped meaning they Javascript variables are untyped meaning they can hold any data type. can hold any data type.

What is a Data Type?What is a Data Type? A data type is a type of value that can be A data type is a type of value that can be

represented or manipulated in javascript.represented or manipulated in javascript.

Primitive Data TypesPrimitive Data Types

Numbers – javascript recognizes integers, Numbers – javascript recognizes integers, hexadecimal and octal literals, floating-point hexadecimal and octal literals, floating-point literals (decimals)literals (decimals)

Strings – sequence of characters contained Strings – sequence of characters contained between double quotes or single quotes.between double quotes or single quotes.

Booleans – data type that is a result of a Booleans – data type that is a result of a comparison and can contain only 2 values – comparison and can contain only 2 values – true or false.true or false.

Composite Data Types - ObjectsComposite Data Types - Objects

An object an be an unordered collection of named An object an be an unordered collection of named values. These are often referred to as the properties of values. These are often referred to as the properties of that object.that object. ex: a web form is an object – the properties you set are ex: a web form is an object – the properties you set are

name, method, action. You can read any of those properties name, method, action. You can read any of those properties like this: document.form1.actionlike this: document.form1.action

ex: a web page itself is an object referred to as the ex: a web page itself is an object referred to as the document. There are properties you can read about that document. There are properties you can read about that document, but there are methods you can perform on that document, but there are methods you can perform on that object such as writing to it: document.write(“Hello object such as writing to it: document.write(“Hello World”);World”);

Composite Data Types - ObjectsComposite Data Types - Objects

An object can be an ordered collection of An object can be an ordered collection of numbered values. These are called arrays.numbered values. These are called arrays. An array is a collection of data values that are An array is a collection of data values that are

stored in the object and identified by an index.stored in the object and identified by an index. Array indexes start at 0.Array indexes start at 0. Declare a new array using the keyword Array:Declare a new array using the keyword Array:

var arrvalues = new Array();var arrvalues = new Array();

var arrvalues = new Array(10);var arrvalues = new Array(10);

functionfunction

A function is a predefined block of code that A function is a predefined block of code that can be executed when called.can be executed when called. A function can be defined by the programmerA function can be defined by the programmer

function checkFields()function checkFields() function setvalues(x,y)function setvalues(x,y)

A function can be predefined by javascript:A function can be predefined by javascript: document.write(“Hello World”);document.write(“Hello World”); Math.round(x);Math.round(x);

Functions cont.Functions cont.

Functions accept arguments or parametersFunctions accept arguments or parameters Parameters are defined in the () of the function Parameters are defined in the () of the function

declarationdeclaration function setvalues(x,y) accepts two arguments. When function setvalues(x,y) accepts two arguments. When

you call this function in your web page, you have to you call this function in your web page, you have to send it two arguments or you will get an error.send it two arguments or you will get an error.

Function Math.round(x) requires one argument. This Function Math.round(x) requires one argument. This argument should be a number type so the math function argument should be a number type so the math function can be performed.can be performed.

null and undefinednull and undefined

null is a special value that indicates no value. null is a special value that indicates no value. If the value is returned as null, you know it If the value is returned as null, you know it does not contain a valid data typedoes not contain a valid data type

undefined is returned when a variable that has undefined is returned when a variable that has been declared has no value assigned to it or an been declared has no value assigned to it or an object does not have a property defined for it.object does not have a property defined for it.

isNaN isNaN

There is a special javascript function you can There is a special javascript function you can use to determine if a value is a number or not.use to determine if a value is a number or not. If isNaN(x) returns true, then the number passed is If isNaN(x) returns true, then the number passed is

not a number. It is a string or a boolean.not a number. It is a string or a boolean. If isNaN(x) returns false, then the number passed If isNaN(x) returns false, then the number passed

to the function is a number.to the function is a number. This will be used to determine if a value is a This will be used to determine if a value is a

number that can be passed to the Math functions or number that can be passed to the Math functions or if a value entered into a zip code field is a number, if a value entered into a zip code field is a number, if not, make them enter it again.if not, make them enter it again.

Data Type ConversionsData Type Conversions

Numbers to Strings:Numbers to Strings: Use simple concatenation with a stringUse simple concatenation with a string

var n= 5;var n= 5;

var strn = n + “ is my favorite number.”;var strn = n + “ is my favorite number.”;

Use the toString methodUse the toString method var strn = n.toString();var strn = n.toString();

Data Type ConversionData Type Conversion

Other methods for converting numbers to Other methods for converting numbers to strings: var n=123456.789strings: var n=123456.789 n.toFixed(0);n.toFixed(0); //”123457”//”123457” n.toFixed(2); //”123456.79”n.toFixed(2); //”123456.79” n.toExponential(1); //”1.2e+5”n.toExponential(1); //”1.2e+5” n.toExponential(3); //”1.235e+5”n.toExponential(3); //”1.235e+5” n.toPrecision(7);n.toPrecision(7); //”123456.8”//”123456.8”

Data Type ConversionData Type Conversion

Strings to Numbers:Strings to Numbers: When a string is used in a numerical context it is When a string is used in a numerical context it is

automatically converted to a number: automatically converted to a number: var product = “22” + “15”;var product = “22” + “15”;

Explicitly convert by using the Number() function:Explicitly convert by using the Number() function:var x=“22”;var x=“22”;var number = Number(x);var number = Number(x);

Data Type ConversionData Type Conversion

parseInt() can be used to retrieve an integer at parseInt() can be used to retrieve an integer at the beginning of a string:the beginning of a string:parseInt(“3 blind mice”)parseInt(“3 blind mice”) //returns 3//returns 3parseInt(“12.34”)parseInt(“12.34”) // returns 12// returns 12

parseFloat() can be used to retrieve integers parseFloat() can be used to retrieve integers and floating point numbers in a string:and floating point numbers in a string:parseFloat(“3.14”)parseFloat(“3.14”) //returns 3.14//returns 3.14parseFloat(“12.5 meters”)parseFloat(“12.5 meters”) //returns 12.5//returns 12.5

Data Type ConversionsData Type Conversions

If parseInt() or parseFloat() cannot convert a If parseInt() or parseFloat() cannot convert a string to a number, it returns NaNstring to a number, it returns NaN parseInt(“eleven”)parseInt(“eleven”) //returns NaN//returns NaN parseFloat(“$54.45”)parseFloat(“$54.45”) //returns NaN//returns NaN

Data Type ConversionData Type Conversion

Javascript will automatically convert boolean Javascript will automatically convert boolean values:values: To numbers: true will convert to 1, false will To numbers: true will convert to 1, false will

convert to 0convert to 0 To strings: true will convert to “true”, false will To strings: true will convert to “true”, false will

convert to “false”convert to “false” Any number other than 0 or NaN is automatically Any number other than 0 or NaN is automatically

converted to true, 0 or NaN is converted to falseconverted to true, 0 or NaN is converted to false Explicitly convert by using Boolean() function:Explicitly convert by using Boolean() function:

var booleanvalue = Boolean(x);var booleanvalue = Boolean(x);

Variable ScopeVariable Scope

Region in a program in which a variable is Region in a program in which a variable is defineddefined Global variables – defined everywhere in your Global variables – defined everywhere in your

javascript codejavascript code Local variables – defined within the function from Local variables – defined within the function from

which it was declared. Function parameters are which it was declared. Function parameters are considered local to that function.considered local to that function.

Scope exampleScope example

<script language = “javascript”><script language = “javascript”>var val;var val;function getvalues(value1, value2)function getvalues(value1, value2){{

var newvalue;var newvalue;}}function setvalues(value1, value2)function setvalues(value1, value2){{

newvalue = value1;newvalue = value1;val = value2;val = value2;

}}</script></script>

Arithmetic OperatorsArithmetic Operators

Addition +Addition + Adds two numbers togetherAdds two numbers together Concatenates two strings togetherConcatenates two strings together

Subtraction –Subtraction – Attempt to subtract the second number from the first Attempt to subtract the second number from the first

numbernumber Multiplication *Multiplication *

Attempts to multiply two numbers (also called operands)Attempts to multiply two numbers (also called operands) Division /Division /

Attempts to divide the first number by the secondAttempts to divide the first number by the second

Arithmetic OperatorsArithmetic Operators

Modulo %Modulo % Returns the remainder when the first operator is Returns the remainder when the first operator is

divided by the second a certain number of timesdivided by the second a certain number of times Increment ++Increment ++

Increments the operand by 1 or adds 1Increments the operand by 1 or adds 1 Decrement --Decrement --

Decrements the operand by 1 or subtracts 1Decrements the operand by 1 or subtracts 1

Order of PrecedenceOrder of Precedence

Arithmetic equations are read from left to right Arithmetic equations are read from left to right If there is only addition and subtraction, they will If there is only addition and subtraction, they will

be done in the order they appearbe done in the order they appear If there is only multiplication and division they If there is only multiplication and division they

will be done in the order they appear.will be done in the order they appear. If there is a mixture of addition, subtraction, If there is a mixture of addition, subtraction,

multiplication and division, the multiplication and multiplication and division, the multiplication and division will be done first, then the addition and division will be done first, then the addition and subtraction.subtraction.

ExamplesExamples

var x = 20, y = 5, n = 10, m = 2;var x = 20, y = 5, n = 10, m = 2;

var val = x + n – y + m; //evaluates to 27var val = x + n – y + m; //evaluates to 27

var val = n + x / y – n / m;var val = n + x / y – n / m; //evaluates to 9//evaluates to 9

Add (), and anything in the () is done firstAdd (), and anything in the () is done first

var val = (n + x) / y – (n / m); //evaluates to 1var val = (n + x) / y – (n / m); //evaluates to 1

ExamplesExamples

var x = 20;var x = 20;var y = 5;var y = 5;var sum = x + y;var sum = x + y;var diff = x – y;var diff = x – y;var prod = x * y;var prod = x * y;var division = x / y;var division = x / y;x = x++;x = x++;y = y--;y = y--;

if statementif statement

Allows javascript to evaluate a statement and Allows javascript to evaluate a statement and perform an action conditionallyperform an action conditionallyif (condition)if (condition)

{{

//perform javascript code within the curly //perform javascript code within the curly bracketsbrackets

}}

Equality OperatorsEquality Operators

Equality ==Equality == If first operand equals second operand, the If first operand equals second operand, the

condition evaluates to true.condition evaluates to true.

if (x == y)if (x == y)

{{

//do code//do code

}}

if (x== y*4)if (x== y*4)

Identity OperatorIdentity Operator

Identity ===Identity === Compares two operands on strict definitions of Compares two operands on strict definitions of

samenesssameness If both values are different data types, they are not If both values are different data types, they are not

identicalidentical Same value or number they are identicalSame value or number they are identical Same string with the characters in the exact same Same string with the characters in the exact same

positionposition Both boolean values are true or both boolean values are Both boolean values are true or both boolean values are

falsefalse

Inequality OperatorsInequality Operators

Not equal to !=Not equal to != Checks of two values are not equal to each otherChecks of two values are not equal to each other

Not identical to !==Not identical to !== Checks if two values are not identical to each otherChecks if two values are not identical to each other

Comparison OperatorsComparison Operators

Greater than >Greater than > Checks if first operand is greater than the secondChecks if first operand is greater than the second

Less than <Less than < Checks if first operand is less than the secondChecks if first operand is less than the second

Greater than or equal to >=Greater than or equal to >= Checks to see if the first operand is greater than or equal to Checks to see if the first operand is greater than or equal to

the secondthe second Less than or equal to <=Less than or equal to <=

Checks to see if the first operand is less than or equal to the Checks to see if the first operand is less than or equal to the secondsecond

if statement blockif statement block

Can compare more than one condition in a Can compare more than one condition in a single if statementsingle if statement Need to determine the logical operatorNeed to determine the logical operator

and && - used to determine if the first condition and && - used to determine if the first condition statement is true and the second condition statement is statement is true and the second condition statement is true then execute the code in the { }true then execute the code in the { }

or || - used to determine if any of the conditional or || - used to determine if any of the conditional statements evaluates to true, then the code in the {} will statements evaluates to true, then the code in the {} will be executed.be executed.

ExamplesExamples

if ((x > y) && (n > m))if ((x > y) && (n > m))

if ((x == y) && (n > m))if ((x == y) && (n > m))

if ((x == y) || (n > m))if ((x == y) || (n > m))

if ((x > y) || (n > m))if ((x > y) || (n > m))

if ((x ==y) || (n==m))if ((x ==y) || (n==m))

elseelse

The else statement can be attached to the if statement The else statement can be attached to the if statement to execute code if the condition in the if statement to execute code if the condition in the if statement does not evaluate to truedoes not evaluate to true if (condition)if (condition)

{{//executes if condition is true//executes if condition is true

}}elseelse{{

//executes if condition is false//executes if condition is false}}

else ifelse if Combines the else statement with another if Combines the else statement with another if

evaluationevaluation if (condition)if (condition)

{{//executes if condition is true//executes if condition is true

}}else if (condition2)else if (condition2){{

//executes if condition2 is true//executes if condition2 is true}}elseelse{{

//executes if condition and condition2 are //executes if condition and condition2 are falsefalse}}

switch statementswitch statement

Evaluates a condition and lists several possible Evaluates a condition and lists several possible answers. This can be used instead of a very answers. This can be used instead of a very long if/elseif statement. Use the break (or long if/elseif statement. Use the break (or return) to get out of the statement when you return) to get out of the statement when you find a match.find a match.

switch exampleswitch example

var st = document.form1.dlstates.value;var st = document.form1.dlstates.value;var displayst = “”;var displayst = “”;switch (st)switch (st){{

case “IA”:case “IA”:displayst = “Iowa”;displayst = “Iowa”;break;break;

case “MN”:case “MN”:displayst = “Minnesota”;displayst = “Minnesota”;break;break;

case “WI”:case “WI”:displayst = “Wisconsin”;displayst = “Wisconsin”;break;break;

}}

whilewhile

Loop that will execute while a condition is Loop that will execute while a condition is true. The while loop evaluates the condition true. The while loop evaluates the condition before the code is ever executed. The first time before the code is ever executed. The first time through, if the condition evaluates to false, the through, if the condition evaluates to false, the code will never be executed.code will never be executed. while (condition)while (condition)

{{//executes while condition is true//executes while condition is true

}}

while examplewhile example

var cnt = 0;var cnt = 0;

while (cnt <= 10)while (cnt <= 10)

{{

//execute code as long as cnt is less than //execute code as long as cnt is less than or equal to 10or equal to 10

cnt++;cnt++;

}}

do whiledo while

This is very similar to the while loop only the This is very similar to the while loop only the condition is evaluated at the end of the loop so condition is evaluated at the end of the loop so the code will always be executed at least once.the code will always be executed at least once. dodo

{{//executes the first time thru and will //executes the first time thru and will

continue to execute as long as the while condition continue to execute as long as the while condition evaluates to trueevaluates to true} while (condition)} while (condition)

do while exampledo while example

var cnt = 0;var cnt = 0;do do {{

//will execute the first time thru//will execute the first time thrucnt++;cnt++;

} while (cnt <= 10)} while (cnt <= 10)

for loopfor loop

Loop that has a counter and tests the condition Loop that has a counter and tests the condition before the loop is ever executed. There are 3 before the loop is ever executed. There are 3 things you must have in your for declaration:things you must have in your for declaration: The counter variable initialized The counter variable initialized The conditionThe condition The counter variable updated for each loopThe counter variable updated for each loop

for loop examplefor loop example

for (var i=0;i<=dlstate.length;i++)for (var i=0;i<=dlstate.length;i++){{

if (document.form1.dlstates.value == “IA”)if (document.form1.dlstates.value == “IA”){{

document.write(“Iowa”);document.write(“Iowa”);break;break;

}}}}

breakbreak

This can be used to break out of a loop or a This can be used to break out of a loop or a switch statement – once you have completed switch statement – once you have completed the task, there is no need to continue looping.the task, there is no need to continue looping.

Can be used with labels – labels are just Can be used with labels – labels are just identifiers you can use to associated with code, identifiers you can use to associated with code, most often used with loops. You may want to most often used with loops. You may want to use this with a nested loop.use this with a nested loop.

break examplebreak example

Outerloop:Outerloop:for (var i=0;i<10;i++)for (var i=0;i<10;i++){{

innerloop:innerloop:for (var j=0;j<10;j++)for (var j=0;j<10;j++){{

if (j>3) break;if (j>3) break; //if (i==2) break innerloop;if (i==2) break innerloop;if (i==4) break outerloop;if (i==4) break outerloop;

}}}}

continuecontinue

The continue is also used with loops. It The continue is also used with loops. It indicates the loop should keep going with a indicates the loop should keep going with a new iteration (i++)new iteration (i++)

while loop – expression at the beginning is while loop – expression at the beginning is tested again.tested again.

do/while loop – skips to the bottom of the loop do/while loop – skips to the bottom of the loop to check the expressionto check the expression

for loop – the increment expression is for loop – the increment expression is evaluatedevaluated

continue examplecontinue example

for (var x=0;x<data.length;x++)for (var x=0;x<data.length;x++)

{{

if (data[x] == null) continue;if (data[x] == null) continue;

total += data[x];total += data[x];

}}

try/catch/finallytry/catch/finally

try holds a block of code you want to executetry holds a block of code you want to execute catch hold the code you want executed if an catch hold the code you want executed if an

exception occurs – an exception is basically an exception occurs – an exception is basically an errorerror

finally is code that will be executed regardless finally is code that will be executed regardless of what happens in the try block – usually of what happens in the try block – usually considered “clean up” code.considered “clean up” code.

If you use a try, you must have either a catch If you use a try, you must have either a catch or a finally. You do not need both.or a finally. You do not need both.

ArraysArrays

An array is an object that is an ordered An array is an object that is an ordered collection of values. The values are stored in collection of values. The values are stored in the array and are retrieved by referencing the the array and are retrieved by referencing the array index.array index.

Arrays have one property – length. This is an Arrays have one property – length. This is an integer telling how many elements are in the integer telling how many elements are in the array.array.

Array MethodsArray Methods

.join() – converts all the elements in the array .join() – converts all the elements in the array to strings and concatenates them. You can pass to strings and concatenates them. You can pass in the character you want to separate them. If in the character you want to separate them. If nothing is used, the list of values from the nothing is used, the list of values from the array will be comma delimited.array will be comma delimited.

.sort() – sorts the elements of the array and .sort() – sorts the elements of the array and restores them in the same array – no copy of restores them in the same array – no copy of the array is made.the array is made.

Array’s cont.Array’s cont.

Putting values into arraysPutting values into arraysarrvalue[0] = 1234;arrvalue[0] = 1234;

arrvalue[1] = “Hello World”;arrvalue[1] = “Hello World”;

arrvalue[2] = 3.14;arrvalue[2] = 3.14;

var arrval = new Array(1234, “Hello World”, 3.14);var arrval = new Array(1234, “Hello World”, 3.14);

var arrval = [1234, “Hello World”, 3.14];var arrval = [1234, “Hello World”, 3.14];

Multi dimensional ArraysMulti dimensional Arrays

You cannot have a true multidimensional You cannot have a true multidimensional arrays, but you can store a new array with arrays, but you can store a new array with another array element.another array element.

You can think of it as a table with rows and You can think of it as a table with rows and columns.columns.

Multidimensional Array ex.Multidimensional Array ex.

var table = new Array(10);var table = new Array(10);for (var i=0;i<table.length;i++)for (var i=0;i<table.length;i++)

table[i] = new Array(10);table[i] = new Array(10);

for (var row=0;row<table.length;row++)for (var row=0;row<table.length;row++)

for (var col=0;col<table[row].length;col++)for (var col=0;col<table[row].length;col++)table[row][col] = row*column;table[row][col] = row*column;

var product = table[5][7];var product = table[5][7];

functionsfunctions

A function is a block of javascript code that A function is a block of javascript code that will be written once, but may be executed will be written once, but may be executed several times.several times.

Functions can be passed arguments or Functions can be passed arguments or parameters which are local variables to that parameters which are local variables to that function. The value that is assigned to these function. The value that is assigned to these functions are passed in when the function is functions are passed in when the function is calledcalled

functionfunction

You can name a function anything you want, You can name a function anything you want, as long as it is not a reserved word in as long as it is not a reserved word in Javascript. Make your names meaningful or Javascript. Make your names meaningful or descriptive.descriptive.

If a function has 2 parameters you must pass in If a function has 2 parameters you must pass in two values when the function is called.two values when the function is called.

There is an optional argument that can be There is an optional argument that can be used. used.

functionfunction

function setFields(value1, /* optional */ value2)function setFields(value1, /* optional */ value2){{

//this function takes two arguments, //this function takes two arguments, value1 value1 //is required, value2 is optional//is required, value2 is optional

}}

returnreturn

Functions usually do something and in some Functions usually do something and in some cases they will return a value. The value could cases they will return a value. The value could be a string, it could be a number, it could be a be a string, it could be a number, it could be a boolean.boolean.

<form name=“form1” Method=“POST” <form name=“form1” Method=“POST” onsubmit=“return checkFields(this)” onsubmit=“return checkFields(this)” action=“processform.asp”>action=“processform.asp”>

returnreturn

function checkFields(form)function checkFields(form){{

//do all your checks to see if the data entered in //your form is valid.//do all your checks to see if the data entered in //your form is valid.if (form.txtFirstName.value == “”)if (form.txtFirstName.value == “”){{

alert(“You must enter a first name);alert(“You must enter a first name);form.txtFirstName.focus();form.txtFirstName.focus();return false;return false;

}}

//if form data is valid, return true and the form is submitted.//if form data is valid, return true and the form is submitted.return true;return true;

}}

StringsStrings

Property – length – returns the number of Property – length – returns the number of characters in a stringcharacters in a string

MethodsMethods charAt() – extracts the character at a given positioncharAt() – extracts the character at a given position indexOf() – searches string for a character or indexOf() – searches string for a character or

substring and returns it’s numerical position.substring and returns it’s numerical position. replace() – performs a search and replace operationreplace() – performs a search and replace operation split() – splits the string into an array of stringssplit() – splits the string into an array of strings

stringsstrings

Methods cont.Methods cont. substring() – extracts a substring of a stringsubstring() – extracts a substring of a string toUpperCase() – returns a copy of the string with toUpperCase() – returns a copy of the string with

all upper case letters.all upper case letters. toLowerCase() – returns a copy of the string in all toLowerCase() – returns a copy of the string in all

lower case letters.lower case letters.

String examplesString examples

var strn = “Welcome to Javascript class”;var strn = “Welcome to Javascript class”;

strn.charAt(5)strn.charAt(5) //returns m//returns m

strn.indexOf(“J”)strn.indexOf(“J”) //returns 11//returns 11

strn.lengthstrn.length //returns 27//returns 27

strn.replace(/class/i, “Class”) //class is Classstrn.replace(/class/i, “Class”) //class is Class

var arrstrn = strn.split(“ “)var arrstrn = strn.split(“ “) //returns an array//returns an array

strn.substring(0,7)strn.substring(0,7) //returns Welcome//returns Welcome

String examplesString examples

strn.toUpperCase()strn.toUpperCase()

//returns “WELCOME TO JAVASCRIPT //returns “WELCOME TO JAVASCRIPT CLASS”CLASS”

strn.toLowerCase()strn.toLowerCase()

//returns welcome to javascript class//returns welcome to javascript class

Date()Date()

Allows you to create a new date. May be used Allows you to create a new date. May be used to retrieve current date and time.to retrieve current date and time.

Remember, Javascript is running on the client Remember, Javascript is running on the client machine. If you use the Date() functions, you machine. If you use the Date() functions, you are reading the date and/or time on the clients are reading the date and/or time on the clients machine.machine.

Refer to page 613 for all the methods you can Refer to page 613 for all the methods you can invoke on the Date() object.invoke on the Date() object.

Web BrowsersWeb Browsers

Javascript is standardized and all modern Javascript is standardized and all modern browsers support it.browsers support it.

Different platforms, Mac OS, Windows, Different platforms, Mac OS, Windows, Linux, however, may differ in their support of Linux, however, may differ in their support of Javascript.Javascript.

http://www.quirksmode.org/dom/ http://webdevout.net/browser_support.phphttp://webdevout.net/browser_support.php

Javascript SecurityJavascript Security

Javascript can open a window, but pop-up blocker Javascript can open a window, but pop-up blocker may restrict it.may restrict it.

Javascript can close a window, but usually, a Javascript can close a window, but usually, a confirmation is required.confirmation is required.

Javascript can not hide the destination of a link when Javascript can not hide the destination of a link when you mouse over it.you mouse over it.

Javascript cannot open windows that are too small.Javascript cannot open windows that are too small. Javascript cannot set the value of a file upload.Javascript cannot set the value of a file upload. Javascript cannot read the content of a document Javascript cannot read the content of a document

other than the document it resides on.other than the document it resides on.

Window ObjectWindow Object

The window object is the global object for The window object is the global object for client side scripting.client side scripting.

Some of these features may be hampered by Some of these features may be hampered by modern security features. modern security features.

TimerTimer

Timer allows you to execute Javascript code in Timer allows you to execute Javascript code in the future.the future.

setTimeout() schedules a function to run after setTimeout() schedules a function to run after a specified number of milliseconds passesa specified number of milliseconds passes

clearTimeout() will cancel the scheduled clearTimeout() will cancel the scheduled execution.execution.

setInterval() invokes a function at set intervalssetInterval() invokes a function at set intervals clearInterval() clears the scheduled intervalclearInterval() clears the scheduled interval

locationlocation

Location property references the location Location property references the location object or the current URL of the windowobject or the current URL of the window

You can read the URL of the pageYou can read the URL of the page You can get the arguments that were passed as You can get the arguments that were passed as

part of a query stringpart of a query string You can load a new document into the You can load a new document into the

windowwindow

historyhistory

history.back() – takes the user back one page history.back() – takes the user back one page to the last visited document.to the last visited document.

history.forward() – takes the user forward one history.forward() – takes the user forward one page in the list of visited documents.page in the list of visited documents.

This is very similar to using the Back and This is very similar to using the Back and Forward key on the browser window. Forward key on the browser window.

Using these will allow you to provide your Using these will allow you to provide your own navigation on a document.own navigation on a document.

Window sizeWindow size

Overall size of the browser windowOverall size of the browser window window.outerwidthwindow.outerwidth window.outerlengthwindow.outerlength

Position of the browserPosition of the browser window.screenxwindow.screenx window.screenywindow.screeny

Window sizeWindow size

Size of the view point in which the HTML document Size of the view point in which the HTML document is displayedis displayed window.innerWidthwindow.innerWidth window.innerHeightwindow.innerHeight

Specify the horizontal and vertical scrollbars. They Specify the horizontal and vertical scrollbars. They are used to specify between document and window are used to specify between document and window coordinates. They specify the part of the document in coordinates. They specify the part of the document in the upper left hand cornerthe upper left hand corner window.pageXOffsetwindow.pageXOffset window.pageYOffsetwindow.pageYOffset

Navigator ObjectNavigator Object

Used to get information about the browser the client Used to get information about the browser the client is using.is using. appName – name of the browserappName – name of the browser appVersion – displays the version number – may say 4.0 to appVersion – displays the version number – may say 4.0 to

indicate compatibility with 4indicate compatibility with 4thth generation browsers generation browsers userAgent – displays information contained in both userAgent – displays information contained in both

appName and appVersionappName and appVersion appCodeName – code name of browser – IE and Netscape appCodeName – code name of browser – IE and Netscape

use Mozillause Mozilla platform – hardware platformplatform – hardware platform

window.openwindow.open

Allows you to open a new window – it takes 4 Allows you to open a new window – it takes 4 optional arguments:optional arguments: URL of the document to be displayedURL of the document to be displayed Name of the window – serves as the target. If the window Name of the window – serves as the target. If the window

is already opened with that name, it loads the new is already opened with that name, it loads the new document in it. Keeps the user from having several document in it. Keeps the user from having several windows open at once.windows open at once.

Features – can set the window size and GUI decorationsFeatures – can set the window size and GUI decorations Boolean value – used in conjunction with the second Boolean value – used in conjunction with the second

argument to determine whether or not URL in the first argument to determine whether or not URL in the first argument should replace the current windows URL in the argument should replace the current windows URL in the browsing history.browsing history.

window.open examplewindow.open example

var w = window.open(“newpage.html”, var w = window.open(“newpage.html”, “newwindow”,”width=400,height=350,status=“newwindow”,”width=400,height=350,status=yes,resizable=yes”,false);yes,resizable=yes”,false);

Window.closeWindow.close

window.close() – closes the current window.window.close() – closes the current window. The user will be prompted with a confirm box The user will be prompted with a confirm box

if they actually want to close the window or if they actually want to close the window or not.not.

Setting focusSetting focus

window.focus() sets focus to that window and window.focus() sets focus to that window and makes it the top level window on the stackmakes it the top level window on the stack

window.blur() relinquishes the keyboards window.blur() relinquishes the keyboards focus on that window.focus on that window.

W3C DOMW3C DOM

Document Object ModelDocument Object Model Displays the document in a tree structure - see Displays the document in a tree structure - see

page 308 for example.page 308 for example. Nodes – the node interface defines properties Nodes – the node interface defines properties

and methods for traversing through the tree.and methods for traversing through the tree. Different types of nodes – page 309Different types of nodes – page 309

Finding Elements in a DocumentFinding Elements in a Document

getElementByTagName() gets the element by the tag getElementByTagName() gets the element by the tag name and all its elementsname and all its elements getElementByTagName(“body”) will return an array of all getElementByTagName(“body”) will return an array of all

the elements in the body of an HTML pagethe elements in the body of an HTML page getElementById() – returns only the single element of getElementById() – returns only the single element of

the matching id. It does not return an arraythe matching id. It does not return an array getElementById(“txtFirstName”) will return this element getElementById(“txtFirstName”) will return this element

and we can reference attribute of this element onlyand we can reference attribute of this element only

Cont.Cont.

getElementsByName() – returns an array of getElementsByName() – returns an array of elements with that nameelements with that name getElementsByName(“rdoConversionTypes”)[x]getElementsByName(“rdoConversionTypes”)[x]

innerHTMLinnerHTML

Used to dynamically write or change the html Used to dynamically write or change the html text in an HTML documenttext in an HTML document

var table = document.createElement(“table”);var table = document.createElement(“table”);

table.border = 1;table.border = 1;

table.innerHTML = table.innerHTML = “<tr><th>Type</th><th>Value</th></tr>”;“<tr><th>Type</th><th>Value</th></tr>”;

AttributesAttributes

setAttribute() – sets an attribute of an element.setAttribute() – sets an attribute of an element.document.form1.setAttrributes(“action”, “processform.asp”);document.form1.setAttrributes(“action”, “processform.asp”);

removeAttribute() – removes an attribute of an removeAttribute() – removes an attribute of an elementelementvar spantag = document.getElementById(“headerspan”);var spantag = document.getElementById(“headerspan”);

spantag.removeAttribute(“align”);spantag.removeAttribute(“align”); getAttribute() – retrieves the attribute of an elementgetAttribute() – retrieves the attribute of an element

document.form1.getAttribute(“action”)document.form1.getAttribute(“action”)

CSS and DHTMLCSS and DHTML

You can change the style of an element by You can change the style of an element by referencing the style property and setting the referencing the style property and setting the valuevalue document.getElementById(“spouseinfo”).style.document.getElementById(“spouseinfo”).style.

display = “none”;display = “none”; document.getElementById(“pagetitle”).style.color document.getElementById(“pagetitle”).style.color

= “red”;= “red”; See pages 347-349 for properties and valuesSee pages 347-349 for properties and values

PositioningPositioning

absolute – the position on the page is absolute absolute – the position on the page is absolute and not part of the flow of the page. It is and not part of the flow of the page. It is positioned in regard to the <body> or, if nested positioned in regard to the <body> or, if nested inside another positioned element, relative to inside another positioned element, relative to that element.that element.

fixed – set the position in respect to the fixed – set the position in respect to the browser window. Fixed positioned elements browser window. Fixed positioned elements are always visible and do not scroll with the are always visible and do not scroll with the document.document.

PositioningPositioning

relative – an element is laid out according to relative – an element is laid out according to the normal flow of the document. When the the normal flow of the document. When the position is relative, the position is adjusted position is relative, the position is adjusted based on where it’s normal position.based on where it’s normal position.

visibility vs. displayvisibility vs. display

visibility determines whether an element if visibility determines whether an element if visible or not visible or not document.getElementById(“spouseinfo”).style.document.getElementById(“spouseinfo”).style.

visibility = “visible”visibility = “visible” document.getElementById(“spouseinfo”).style.document.getElementById(“spouseinfo”).style.

visibility = “hidden”visibility = “hidden” Using this style element will reserve the space Using this style element will reserve the space

on the layout of the page.on the layout of the page.

displaydisplay

display will hide elements or display them display will hide elements or display them without regard to the page layout. If an without regard to the page layout. If an element is hidden, there is not space reserved element is hidden, there is not space reserved for this element.for this element. document.getElementById(“spouseinfo”).style.document.getElementById(“spouseinfo”).style.

display = “none” display = “none” document.getElementById(“spouseinfo”).style.document.getElementById(“spouseinfo”).style.display = “”display = “”

See page 348 for other values for displaySee page 348 for other values for display

External StylesheetsExternal Stylesheets

You can link to an external stylesheetYou can link to an external stylesheet <link rel=“stylesheet” type=“text/css” <link rel=“stylesheet” type=“text/css”

href=“ss0.css” id=“ss0”>href=“ss0.css” id=“ss0”> You can have alternate stylesheets that are You can have alternate stylesheets that are

disabled by defaultdisabled by default <link rel=“alternate stylesheet” type=“text/css” <link rel=“alternate stylesheet” type=“text/css”

href=“ss1.css” id=“ss1”>href=“ss1.css” id=“ss1”>

External CSSExternal CSS

function enableSS(sheetid,enabled)function enableSS(sheetid,enabled)

{{

document.getElementById(sheetid).disabled = document.getElementById(sheetid).disabled = false;false;

}}

<input type=“checkbox” <input type=“checkbox” onclick=“enableSS(‘ss1’,this.checked)”>Boldonclick=“enableSS(‘ss1’,this.checked)”>Bold

EventsEvents

See page 390 and 391 for list of event handlersSee page 390 and 391 for list of event handlers Set as an attribute:Set as an attribute:

<input type = “button” name=“b1” value = “Press <input type = “button” name=“b1” value = “Press Me” onclick=“sendUser()”>Me” onclick=“sendUser()”>

Set as a property:Set as a property: document.form1.b1.onclick = sendUser();document.form1.b1.onclick = sendUser();

DOM Level 2DOM Level 2

Supported by all browsers except Internet Supported by all browsers except Internet ExplorerExplorer

Event Handler RegistrationEvent Handler Registration Use addEventListenerUse addEventListener document.form1.addEventListener(“submit”, document.form1.addEventListener(“submit”,

checkFields(e.target), false)checkFields(e.target), false) document.form1.addEventListener(“click”, document.form1.addEventListener(“click”,

showdiv, true)showdiv, true)

Internet Explorer Event ModelInternet Explorer Event Model

Supported by IE 4 and aboveSupported by IE 4 and above Not passed to an event-handler function, it Not passed to an event-handler function, it

becomes a property of the window objectbecomes a property of the window object attachEventattachEvent

document.getElementById(“b1”).attachEvent(document.getElementById(“b1”).attachEvent(“onclick”, nameoffunction)“onclick”, nameoffunction)

FormsForms

Form ObjectForm Object You can use the submit() function in javascript to You can use the submit() function in javascript to

submit the form, very similar to the Submit buttonsubmit the form, very similar to the Submit button You can use the reset() function in javascript to You can use the reset() function in javascript to

reset the form, very similar to the Reset button.reset the form, very similar to the Reset button. You can use the onsubmit property of a form to You can use the onsubmit property of a form to

call a validation function and submit the form call a validation function and submit the form upon completion with a return of true.upon completion with a return of true.

FormsForms

You can refer to the form and it’s elements by You can refer to the form and it’s elements by name, or you can traverse through the form name, or you can traverse through the form and all it’s elements as an arrayand all it’s elements as an arrayvar form = new Object(); var form = new Object(); form = document.getElementById(“form1”),form = document.getElementById(“form1”),for (var x=0;x<form.length;x++)for (var x=0;x<form.length;x++){{

alert(x + “ “ + form[x].name)alert(x + “ “ + form[x].name)}}

FormsForms

Form elements (page 440 & 441)Form elements (page 440 & 441) Name - every form element needs a name if the form is Name - every form element needs a name if the form is

being submitted server side. It is best to give the form itself being submitted server side. It is best to give the form itself a name.a name.<form name=“form1”><form name=“form1”>document.form1document.form1document.forms[0]document.forms[0]<form name = “address”><form name = “address”> <input type = “text” name=“zip” value=“”><input type = “text” name=“zip” value=“”>document.address.zipdocument.address.zipdocument.forms[1].elements[4]document.forms[1].elements[4]

FormsForms

PropertiesProperties Type – string telling the type of the form elementType – string telling the type of the form element form – reference to the form which contains it.form – reference to the form which contains it. name – string depicting the name you gave the name – string depicting the name you gave the

element.element. value – a string that you can set as a default value value – a string that you can set as a default value

when the form loads or set in your javascript with when the form loads or set in your javascript with a value retrieved server side.a value retrieved server side.

FormsForms

Event HandlersEvent Handlers onclick – triggered when user clicks the elementonclick – triggered when user clicks the element onchange – triggered when the user changes the onchange – triggered when the user changes the

value of a text field or selection boxvalue of a text field or selection box onfocus – triggered when the element receives onfocus – triggered when the element receives

input focusinput focus onblur – triggered when the element loses input onblur – triggered when the element loses input

focusfocus

Push ButtonPush Button

Has no default value of it’s own and is pretty Has no default value of it’s own and is pretty useless without an onclick eventuseless without an onclick event

Works just like a link but gives the visual of a Works just like a link but gives the visual of a buttonbutton

Can use the <input> or <button> tagCan use the <input> or <button> tag Using the <button> allows you to put text or an Using the <button> allows you to put text or an

image as your buttonimage as your button Properties are the sameProperties are the same

Toggle buttonsToggle buttons

Radio buttons or checkbox elementsRadio buttons or checkbox elements Can capture the onclick event. Some newer Can capture the onclick event. Some newer

browsers also support the onchange eventbrowsers also support the onchange event When the user clicks one of these elements, the When the user clicks one of these elements, the

state of that element changes from unchecked to state of that element changes from unchecked to checked. You can read the checked property to checked. You can read the checked property to determine if it has been chosendetermine if it has been chosen

if (document.form1.rdoMF[0].checked == true)if (document.form1.rdoMF[0].checked == true)

Text boxesText boxes

Textbox, textarea, password and file elementsTextbox, textarea, password and file elements Can use all the form eventsCan use all the form events Most commonly you read or set the value propertyMost commonly you read or set the value property

var name = document.form1.txtname.value;var name = document.form1.txtname.value;

if ((name == “”) || (name == “ “))if ((name == “”) || (name == “ “))

{{

alert(“You must enter a name”);alert(“You must enter a name”);

}}

Select and Option ElementsSelect and Option Elements

Captures the onchange eventCaptures the onchange event The select tag does not contain the value property, The select tag does not contain the value property,

each of the option tags do.each of the option tags do. If the user can only choose one option, you can use If the user can only choose one option, you can use

the selectedIndex property to return the index or the the selectedIndex property to return the index or the value property to obtain the value of the selected value property to obtain the value of the selected optionoption

If the user can choose multiple options, you need to If the user can choose multiple options, you need to loop through the array of options and check the loop through the array of options and check the selected property of each option.selected property of each option.

Select and Options ElementsSelect and Options Elements

You can read the text of an option and change You can read the text of an option and change the value the user sees by access the text the value the user sees by access the text property of the options arrayproperty of the options arraydocument.form1.dlMonth.options[2].text = document.form1.dlMonth.options[2].text = “March Madness”;“March Madness”;

You can make an option disappear by setting it You can make an option disappear by setting it to nullto nulldocument.form1.dlMonth.options[2] = null;document.form1.dlMonth.options[2] = null;

Select and Option ElementsSelect and Option Elements

You can add an option to a select groupYou can add an option to a select group Use new Option constructorUse new Option constructor

What the user seesWhat the user sees Value submitted to the formValue submitted to the form Boolean to set the defaultSelected propertyBoolean to set the defaultSelected property Boolean to set the selected propertyBoolean to set the selected property

var vacation = new Option(“Vacation Month”,var vacation = new Option(“Vacation Month”,“vm”, false, false)“vm”, false, false)

ExamplesExamples

//check if textbox has something in it//check if textbox has something in itvar txtname = document.form1.txtname.value;var txtname = document.form1.txtname.value;if ((txtname == “”) || (txtname == “ “))if ((txtname == “”) || (txtname == “ “)){{

alert(“You must enter a name.”);alert(“You must enter a name.”);document.form1.txtname.focus();document.form1.txtname.focus();return false;return false;

}}

ExamplesExamples

//checks to see if radio button is selected//checks to see if radio button is selected

if ((document.form1.rdoMF[0].checked == false) if ((document.form1.rdoMF[0].checked == false) && (document.form1.rdoMF[1].checked == && (document.form1.rdoMF[1].checked == false))false))

{{

alert(“You must choose Male or Female.”);alert(“You must choose Male or Female.”);

return false;return false;

}}

Examples Examples

//check to see if user selected something in the //check to see if user selected something in the drop down boxdrop down box

if (document.dlMonth.selectedIndex == 0)if (document.dlMonth.selectedIndex == 0)

{{

alert(“You must select a valid month.”);alert(“You must select a valid month.”);

return false;return false;

}}

ExampleExample

//check to see if zip code entered is 5 digits//check to see if zip code entered is 5 digitsvar zip = document.form1.zip.value;var zip = document.form1.zip.value;if (zip.length < 5)if (zip.length < 5){{

alert(“You must entere a valid zip code”);alert(“You must entere a valid zip code”);document.form1.zip.focus();document.form1.zip.focus();return false;return false;

}}

ExampleExample

//check to see if zip code entered is a number//check to see if zip code entered is a numberif (isNaN(document.form1.zip.value))if (isNaN(document.form1.zip.value)){{

alert(“You must enter a valid numeric zip alert(“You must enter a valid numeric zip code”);code”);document.form1.zip.focus()document.form1.zip.focus()return false;return false;

}}

CookiesCookies

A cookie is a small amount of data stored by A cookie is a small amount of data stored by the web browser and associated with a the web browser and associated with a particular web page or web site.particular web page or web site.

Cookies are written to the clients machine.Cookies are written to the clients machine. Cookies are limited in size to 4kb in size and Cookies are limited in size to 4kb in size and

the browsers only allow storage of 300 cookies the browsers only allow storage of 300 cookies total, 20 per web server.total, 20 per web server. Modern browsers allow more than 300 but if file Modern browsers allow more than 300 but if file

size is greater than 4kb, only 4 kb will be stored.size is greater than 4kb, only 4 kb will be stored.

Cookie AttributesCookie Attributes

Cookies are stored with a name=value format.Cookies are stored with a name=value format. expires or max-age – the lifespan of a cookie expires or max-age – the lifespan of a cookie

only lasts as long as the browser is open. If only lasts as long as the browser is open. If you want it to last longer you must set the you want it to last longer you must set the expire attribute to a certain date. In place of expire attribute to a certain date. In place of this you can use the max-age attribute which this you can use the max-age attribute which displays how long to keep the cookie alive in displays how long to keep the cookie alive in milliseconds.milliseconds.

Cookie AttributesCookie Attributes

Path – which specifies the web with which the cookie Path – which specifies the web with which the cookie is associated. You can set that path to allow any page is associated. You can set that path to allow any page with the path string in it to be viewed by that web with the path string in it to be viewed by that web site.site.

Domain – this defaults to the host name but you can Domain – this defaults to the host name but you can set this to a string to allow any page on with that set this to a string to allow any page on with that domain on any server. You can only set the domain to domain on any server. You can only set the domain to a domain on your server.a domain on your server.

Secure – all cookies are secure and can be transmitted Secure – all cookies are secure and can be transmitted over an http connection. If it is secure, it must be a over an http connection. If it is secure, it must be a https connectionhttps connection