Download presentation
Presentation is loading. Please wait.
1
Introduction to Programming the WWW I
CMSC Winter 2004 Lecture 16 Introduction to JavaScript 3
2
Introduction to JavaScript 3
Today’s Topics Expressions and statements (cont’d) Using events Working with Objects (window, location, history and navigator) Working with Forms Introduction to JavaScript 3
3
Review: Automatic Arrays in Document Objects
How to access the object in these arrays, for example, a link in the document? By array syntax. If this link is the first link definition in the document (in source code order), the reference would be document.links[0] Or you can also use the name (as a string) in array syntax, as follows: document.links["home"] Does not work in IE! Examples: Introduction to JavaScript 3
4
Expressions and Operators
Logical Operators Used for comparing two Boolean operands for equality Comparison returns a Boolean value Comprised of both binary and unary operators Introduction to JavaScript 3
5
Introduction to JavaScript 3
6
Introduction to JavaScript 3
Logical Operators Examples: BooleanVariables.html LogicalExamples.html Introduction to JavaScript 3
7
Expressions and Operators
Working with Strings JavaScript has two operators that can be used with Strings to combine two strings Concatenation operator (+) var oneString = “one”; var anotherString = oneString + “, two, three, …”; Assignment operator (+=) oneString += “, two, three, …”; Introduction to JavaScript 3
8
Expressions and Operators
String Object Literal strings and string variables in JavaScript are represented by a String object The String object contains methods for manipulating text strings Introduction to JavaScript 3
9
Expressions and Operators
String Object length property Returns the number of characters in a string Parsing Act of extracting characters or substrings from a larger string Introduction to JavaScript 3
10
Expressions and Operators
String Object Parsing using the split() built-in function Reference: Javascript: the Definitive Guide, p 529. stringVariable.split(delimiter). Returns an array of strings, created by splitting string into substrings at the boundaries specified by delimiter. Introduction to JavaScript 3
11
Expressions and Operators
String Object Parsing using the split() built-in function. Example: var myVar = “John Barr”; var newVar = myVar.split(“ “); newVar contains [“John”, “Barr”] Introduction to JavaScript 3
12
Expressions and Operators
String Object Parsing using the split() built-in function. Example: var myVar = “red;blue;green;yellow”; var newVar = myVar.split(“;“); newVar contains [“red”, “blue”.”green”,”yellow”] Introduction to JavaScript 3
13
Expressions and Operators
Example: StringExamples.html Introduction to JavaScript 3
14
Expressions and Operators
Operator Precedence Order of priority in which operations in an expression are evaluated Expressions are evaluated On a left-to-right basis With the highest priority precedence evaluated first Introduction to JavaScript 3
15
Expressions and Operators
Operator Precedence Parentheses/brackets/dot (( ) [ ] .) Negation/increment (! typeof void) Multiplication/division/modulus (* / %) Addition/subtraction (+ -) Comparison (< <= > >=) Equality (== !=) Logical AND (&&) Logical OR (||) Assignment operators (= += -= *= /= %=) Comma (,) Introduction to JavaScript 3
16
Decision Making Statements
if statements if…else statements Nested if statements switch statements Introduction to JavaScript 3
17
Introduction to JavaScript 3
Decision Making Decision Making Process of determining the order in which statements execute in a program AKA – flow control Decision-Making Structures Special type of JavaScript statements used for making decisions Introduction to JavaScript 3
18
Introduction to JavaScript 3
Decision Making if Statements Used to execute specific programming code if the evaluation of a conditional expression returns a value of true “Do this or don’t do this” Syntax (3 primary parts) if (conditional_expression) { statement(s); } Introduction to JavaScript 3
19
Introduction to JavaScript 3
Decision Making if Statements Operation If the conditional expression is true, the statement(s) is/are executed Control then continues to subsequent code Command block Multiple statements contained within a set of braces (require curly braces) Introduction to JavaScript 3
20
Introduction to JavaScript 3
21
Introduction to JavaScript 3
22
Introduction to JavaScript 3
23
Introduction to JavaScript 3
Decision Making if Statements Conditional Expression Can consist of: Comparison operators Logical operators Combination of the two Must resolve to Boolean value Introduction to JavaScript 3
24
Introduction to JavaScript 3
Decision Making if…else Statements Used to execute one set of code if the evaluation of a conditional expression returns a value of true, otherwise executes another set of code “Do this or do something else” Syntax if (conditional_expression) { statement(s); } else { } Introduction to JavaScript 3
25
Introduction to JavaScript 3
26
Introduction to JavaScript 3
Decision Making Nested if and if…else Statements Nested statements Statements contained within other statements Syntax (variable) if (conditional_expression) { statement(s); } } else { Introduction to JavaScript 3
27
Introduction to JavaScript 3
28
Introduction to JavaScript 3
29
Introduction to JavaScript 3
Decision Making switch Statements Controls program flow by executing a specific set of statements, depending on the value of an expression Syntax switch (expression) { case label1: statement(s); break; case label2: default: } Introduction to JavaScript 3
30
Introduction to JavaScript 3
Decision Making switch Statements Case labels Identify specific code segments Can use a variety of data types as case labels Break statement Used to exit switch statements Default label Contains statements that execute when the condition expression doesn’t match any of the case labels Introduction to JavaScript 3
31
Introduction to JavaScript 3
32
Repetition Statements
while statements do…while statements for statements break/continue statements Introduction to JavaScript 3
33
Introduction to JavaScript 3
Repetition Repetition The if, if…else and switch statements select only a single branch of code to execute, then continue to the statement that follows Loop statements Repeatedly execute a statement or a series of statements while a specific is true or until a specific condition becomes true Introduction to JavaScript 3
34
Introduction to JavaScript 3
Repetition while Statements Used for repeating a statement or a series of statements as long as a given conditional expression evaluates to true Typically uses a counter to keep track of iteration Syntax while (conditional_expression) { statement(s); } Introduction to JavaScript 3
35
Introduction to JavaScript 3
Repetition while Statements Example: var count = 1; while (count <= 5) { document.writeln(count); ++count; } document.writeln(“You have printed 5 numbers.”); Introduction to JavaScript 3
36
Introduction to JavaScript 3
37
Introduction to JavaScript 3
Repetition while Statements Example: var count = 10; while (count > 0) { document.writeln(count); --count; } document.writeln(“We have liftoff.”); Introduction to JavaScript 3
38
Introduction to JavaScript 3
39
Introduction to JavaScript 3
Repetition while Statements Example: var count = 1; while (count <= 100) { document.writeln(count); count *= 2; } Introduction to JavaScript 3
40
Introduction to JavaScript 3
41
Introduction to JavaScript 3
Repetition while Statements Infinite loop A situation in which a loop statement never ends because the conditional expression is never updated or is never false Need to include code within the body of the while statement that changes some part of the conditional expression Should also include code that monitors the conditional expression Introduction to JavaScript 3
42
Introduction to JavaScript 3
Repetition do…while Statements Executes a statement or statements once, then repeats the execution as long as a given conditional expression evaluates to true “Do once, then test to see if it is done again” Syntax do { statement(s); } while (conditional_expression) ; Introduction to JavaScript 3
43
Introduction to JavaScript 3
44
Introduction to JavaScript 3
45
Introduction to JavaScript 3
Repetition for Statements Used for repeating a statement or series of statements as long as a given conditional expression evaluates to true “Do for a prescribed number of iterations” Syntax for (initialization_expression; condition; update_statement) { statement(s); } Introduction to JavaScript 3
46
Introduction to JavaScript 3
Repetition for Statements Steps in processing a for loop Initialization expression is started Only occurs once, when loop is first encountered Evaluate condition If condition == true execute loop body, go to next step If condition == false for statement ends Execute update statement Then return to condition evaluation Introduction to JavaScript 3
47
Introduction to JavaScript 3
48
Introduction to JavaScript 3
49
Introduction to JavaScript 3
50
Introduction to JavaScript 3
Repetition Control break Statements Stop executing the looping statement continue Statements Halts a looping statement and restarts the loop with a new iteration Introduction to JavaScript 3
51
Introduction to JavaScript 3
52
Introduction to JavaScript 3
53
Introduction to JavaScript 3
54
Introduction to JavaScript 3
Using Events About events About HTML tags and events How to use event handlers About links How to use link events How to create an image map Introduction to JavaScript 3
55
Introduction to JavaScript 3
Using Events Understanding Events Event A specific circumstance that is monitored by JavaScript or, A trigger that fires specific JavaScript code in response to a given situation e.g., an action that a user takes Introduction to JavaScript 3
56
Introduction to JavaScript 3
Using Events Understanding Events Events Two basic types User-generated events e.g., mouse-click System-generated events e.g., load event triggered by web browser when HTML document finishes loading Introduction to JavaScript 3
57
Introduction to JavaScript 3
58
Introduction to JavaScript 3
Using Events HTML Tags and Events HTML elements allow user to trigger events <input> tag Creates input fields that interact with users <input type=“input-type”> Type attribute determines type of input field <input type=“text”> creates a text field Name attribute assigns a unique name to the element that JavaScript can use to reference it Introduction to JavaScript 3
59
Introduction to JavaScript 3
60
Introduction to JavaScript 3
61
Introduction to JavaScript 3
Using Events Event Handlers Event handler Code that executes in response to a specific event <HTMLtag eventHandler=“JavaScript-code”> Event handler naming convention Event name with a prefix of “on” E.g., onClick <input type=“button” onClick=“alert(‘You clicked the button!’)”> Introduction to JavaScript 3
62
Introduction to JavaScript 3
Using Events Example: ChangedValue.html Introduction to JavaScript 3
63
Introduction to JavaScript 3
Using Events Event Handlers Built-in JavaScript utility methods alert() method Displays a pop-up dialog box with an OK button prompt() method Displays a pop-up dialog box with a message, a text box, an OK button, and a Cancel button Example prompt.html prompt2.html Introduction to JavaScript 3
64
Introduction to JavaScript 3
Using Events Links Events Primary event is the click event For default operation, no event handler is required Overriding the default click event Add onClick event handler that executes custom code Event handler must return true or false Can use built-in confirm() method to generate Boolean value Introduction to JavaScript 3
65
Introduction to JavaScript 3
66
Introduction to JavaScript 3
67
Introduction to JavaScript 3
Using Events More examples: warnuser.html confirmLinks.html Introduction to JavaScript 3
68
Introduction to JavaScript 3
Using Events Other Links Events MouseOver event Occurs when the mouse moves over a link MouseOut event Occurs when the mouse moves off a link Can be used to change the text that appears in the browser’s status bar Use JavaScript status property for the window object Example: onMouseOver = “window.status = ‘testing, testing, testing….’” Note that some browsers don’t handle onMouseOver changes to the status bar from inside image maps! Introduction to JavaScript 3
69
Introduction to JavaScript 3
Using Events onMouseOver default behavior: display link in status bar if onMouseOver returns true tells the web browser not to perform default behavior if onMouseOver returns false, tells the web browser that it should perform default behavior. backwards from the onClick values! Introduction to JavaScript 3
70
Introduction to JavaScript 3
Using Events default status bar message the defaultStatus property records the message that will always be displayed in the status bar unless another message is explicitly placed there. <body onLoad=“defaultStatus=‘The Dafoe Family’;”> Introduction to JavaScript 3
71
Introduction to JavaScript 3
Using Events Examples: testStatusBar.html CorrectStatus.html BodyParts.html Introduction to JavaScript 3
72
A Simple Image Rollover
<html> <head> <script language="javascript"> function rollover (newpic){ document.picture.src = newpic; } </script> </head> <body> <a href=“#” onMouseOver="rollover('sunflowerlady.jpg');" onMouseOut="rollover('sunflowers.jpg')"> <img src="sunflowers.jpg" name="picture" border="0" > </a> </body> </html> Usually we DO NOT use the following codes since the image objects in some browsers do not respond to mouse events: <img src="sunflowers.jpg" name="picture" border="0" onMouseOver= "rollover('sunflowerlady.jpg');" onMouseOut= "rollover('sunflowers.jpg')"> Introduction to JavaScript 3
73
More Effective Image Rollover
<html> <head> <script language="javascript"> var theOffImage = new Image; var theOnImage = new Image; theOffImage.src ="sunflowers.jpg"; theOnImage.src = "sunflowerlady.jpg"; function rollover (tag){ if (tag == 'on') document.picture.src = theOnImage.src; else document.picture.src = theOffImage.src; } </script> </head><body> <a href=“#” onMouseOver="rollover('on');" onMouseOut="rollover('off')"> <img src="sunflowers.jpg" name="picture" border="0“> </a> </body></html> The simple image rollover may produce an unacceptable delay in retrieving and displaying the 2nd image The new example will improve the efficiency by preloading the images Introduction to JavaScript 3
74
Using Events with Image Maps
Examples: ShowCountry.html Changing images with MouseOver and MouseOut events. Introduction to JavaScript 3
75
Introduction to JavaScript 3
Image Maps Example: changing images with events. <img src=“north_america.gif” usemap=“#northAmerica_map” name=“northAmerica”> <map name=“northAmerica_map”> <area shape=“circle” coords=“44,46,20” nohref onMouseOver=“change_image(‘alaska.gif’);return false” onMouseOut=“reset_image(); return false”> <area shape=“poly” …… rest of html code here ……. </map> Introduction to JavaScript 3
76
Introduction to JavaScript 3
Image Maps Example: changing images with events. <html> <head> <title>North America</title> <script language=“JavaScript”> function change_image(image_name){ document.northAmerica.src = image_name; } function reset_image(){ document.northAmerica.src = “north_america.gif” </script> </head> Introduction to JavaScript 3
77
Introduction to JavaScript 3
Using Events More examples: ImageOver.html ShowAnimal.html ShowAnimal2.html (uses functions) FamilyImageMap.html Introduction to JavaScript 3
78
Working with the Location Object
Allows you to change to a new web page from within JavaScript code Contains several properties and methods for working with the URL of the document currently open in a Web browser window Go to First Slide Introduction to JavaScript 3
79
Working with the Location Object
When you modify any property of the Location object, you generate a new URL The web browser will then automatically attempt to open that new URL Introduction to JavaScript 3
80
Introduction to JavaScript 3
81
Introduction to JavaScript 3
The Location Object Example: location.href = “ Will cause the browser to open the uchicago home page Introduction to JavaScript 3
82
Introduction to JavaScript 3
83
Introduction to JavaScript 3
The Location Object The assign() method is same as the href property: location.assign(“ will cause the uchicago home page to be loaded in the browser. The reload() method is same as the reload button If no argument or argument is false then the page is reloaded only if it has changed If argument is true then the page will always reload Introduction to JavaScript 3
84
Introduction to JavaScript 3
The Location Object The replace() method is similar to the href property: location.assign(“ Difference: replace actually overwrites one document with another Also replaces the old URL entry in the web browser’s history list. The href property opens a different document and adds it to the history list. Introduction to JavaScript 3
85
Introduction to JavaScript 3
The Location Object Example: Redirect.html Redirect2.html Introduction to JavaScript 3
86
Working with the History Object
Maintains a history list of all the documents that have been opened during the current Web browser session Security features History object will not display the URLs on the list In IE: only allows navigation if page is in same domain Introduction to JavaScript 3
87
Introduction to JavaScript 3
88
Working with the History Object
The History Object Example: Introduction to JavaScript 3
89
Working with the Navigator Objects
Used to obtain information about the current web browser Typically used to identify browser Introduction to JavaScript 3
90
Introduction to JavaScript 3
91
Working with Navigator Object
The Navigator Object Example: NavigatorObjects.html BrowserProperties.html document.writeln(“Browser code name: “ + navigator.appCodeName); document.writeln(“Web browser name: “ + navigator.appName); document.writeln(“Web browser version: “ + navigator.appVersion); document.writeln(“Operating platform: “ + navigator.platform); document.writeln(“User agent: “ + navigator.userAgent); Introduction to JavaScript 3
92
Introduction to JavaScript 3
Working with Forms Validating a User's Input to a Form with JavaScript About hidden form fields About the Form object How to reference forms and form elements About form event handlers, methods, and properties How to form data Introduction to JavaScript 3
93
Validating a User’s Input to a Form
Hidden Form Fields Special type of form element that allows the hiding of information from users Created with <input> tag, setting the TYPE attribute to hidden Can be used to store information the program needs later Introduction to JavaScript 3
94
Validating a User’s Input to a Form
The Form Object Enables the use of JavaScript for verifying form information Allows validation before submission to CGI script on server (client-side validation) Minimizes Web traffic Simplifies CGI script Introduction to JavaScript 3
95
The form array contains all forms in the document
The elements[ ] array contains all the elements used in the form. Introduction to JavaScript 3
96
Validating a User’s Input to a Form
The Form Object Referencing Forms and Form Elements Each document object includes a forms[ ] array that contains all of an HTML document’s forms Each form object includes an elements[ ] array that contains all of a form’s elements Placed into array in order they are placed in form To reference third element in second form: document.forms[1].elements[2] Introduction to JavaScript 3
97
Validating a User’s Input to a Form
The Form Object Referencing Forms and Form Elements NAME attribute Allows JavaScript to reference the item (e.g., form, element, etc.) If multiple form elements share the same name, JavaScript creates an array out of those elements Radio buttons document.demographics.ageGroup[1].value Introduction to JavaScript 3
98
Validating a User’s Input to a Form
The Form Object Form Event Handlers onSubmit Executes when a form is submitted to a CGI script using a submit or an image input tag onReset Executes when a reset button is selected on a form Introduction to JavaScript 3
99
Validating a User’s Input to a Form
The Form Object Form Methods Form object contains two methods submit() Used to submit a form without the use of a submit <input> tag reset() Used to clear a form without the use of a reset <input> tag Introduction to JavaScript 3
100
Validating a User’s Input to a Form
The Form Object Form Properties Form object includes: Several properties that correspond to the attributes of the <form> tag Properties containing information about form elements Introduction to JavaScript 3
101
Introduction to JavaScript 3
102
Introduction to JavaScript 3
103
Validating a User’s Input to a Form
Examples: ConfirmForm.html. and ConfirmForm2.html. (simple confirmation examples) PurchaseOrder.html. (confirmation of values before submitting) MathQuiz.html. (using hidden fields) ProductRegistration.html. (using hidden fields for creating a multiple page form). Second form page is ProductInfo.html. Calculator.html. (hidden fields etc.) Introduction to JavaScript 3
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.