Introduction to Programming the WWW I

Slides:



Advertisements
Similar presentations
JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
Advertisements

Java Script Session1 INTRODUCTION.
The Web Warrior Guide to Web Design Technologies
JavaScript Forms Form Validation Cookies. What JavaScript can do  Control document appearance and content  Control the browser  Interact with user.
PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Information Technology Center Hany Abdelwahab Computer Specialist.
Tutorial 4 Decision Making with Control Structures and Statements Section A - Decision Making JavaScript Tutorial 4 -Decision Making with Control.
CST JavaScript Validating Form Data with JavaScript.
1 Events Lect 8. 2 Event-driven Pages one popular feature of the Web is its interactive nature e.g., you click on buttons to make windows appear e.g.,
Chapter 5 Java Script And Forms JavaScript, Third Edition.
Chapter 6: Forms JavaScript - Introductory. Previewing the Product Registration Form.
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
© 2000 – All Rights Reserved - Page 1 Introduction to JavaScript Programming Part Two.
CSS Class 7 Add JavaScript to your page Add event handlers Validate a form Open a new window Hide and show elements Swap images Debug JavaScript.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Using Client-Side Scripts to Enhance Web Applications 1.
Introduction to JavaScript 41 Introduction to Programming the WWW I CMSC Winter 2004 Lecture 17.
JavaScript, Fourth Edition Chapter 5 Validating Form Data with JavaScript.
Client-Side Scripting JavaScript.  produced by Netscape for use within HTML Web pages.  built into all the major modern browsers. properties  lightweight,
20-753: Fundamentals of Web Programming 1 Lecture 12: Javascript I Fundamentals of Web Programming Lecture 12: Introduction to Javascript.
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
Tutorial 5 Windows and Frames Section B - Working with Frames and Other Objects Go to Other Objects.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
JavaScript - Basic Concepts Prepared and Presented by Hienvinh Nguyen, Afshin Tiraie.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved.
Chapter 2: Variables, Functions, Objects, and Events JavaScript - Introductory.
JavaScript, Fourth Edition
JavaScript, Fourth Edition Chapter 4 Manipulating the Browser Object Model.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
ECA 225 Applied Interactive Programming ECA 225 Applied Online Programming control structures, events, objects.
1 CSC160 Chapter 7: Events and Event Handlers. 2 Outline Event and event handlers onClick event handler onMouseOver event handler onMouseOut event handler.
WDMD 170 – UW Stevens Point 1 WDMD 170 Internet Languages eLesson: Variables, Functions and Events (NON-Audio version) © Dr. David C. Gibbs WDMD.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Introduction to JavaScript 21 Introduction to Programming the WWW I CMSC Winter 2004 Lecture 15.
JavaScript Events Java 4 Understanding Events Events add interactivity between the web page and the user You can think of an event as a trigger that.
JavaScript, Sixth Edition
Javascript Basic Concepts Presentation By: Er. Sunny Chanday Lecturer CSE/IT RBIENT.
JavaScript and Ajax (JavaScript Environment) Week 6 Web site:
JavaScript Events. Understanding Events Events add interactivity between the web page and the user Events add interactivity between the web page and the.
Introduction to JavaScript Events Instructor: Sergey Goldman 1.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
 2001 Prentice Hall, Inc. All rights reserved. Outline 1 JavaScript.
XHTML Forms.
Chapter 5 Validating Form Data with JavaScript
Java Script Introduction. Java Script Introduction.
JavaScript and HTML Simple Event Handling 11-May-18.
CHAPTER 10 JAVA SCRIPT.
In this session, you will learn to:
Applied Component I Unit II Introduction of java-script
JavaScript is a programming language designed for Web pages.
Introduction to JavaScript Events
Project 9 Creating Pop-up Windows, Adding Scrolling Messages, and Validating Forms.
Week#2 Day#1 Java Script Course
CHAPTER 4 CLIENT SIDE SCRIPTING PART 2 OF 3
JavaScript and HTML Simple Event Handling 19-Sep-18.
Event Driven Programming & User Defined Functions
WEB PROGRAMMING JavaScript.
Events Comp 205 Fall 2017.
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
Introduction to JavaScript
JavaScript Basics What is JavaScript?
JavaScript is a scripting language designed for Web pages by Netscape.
CIS 136 Building Mobile Apps
Web Programming and Design
JavaScript and HTML Simple Event Handling 26-Aug-19.
JavaScript and HTML Simple Event Handling 4-Oct-19.
Presentation transcript:

Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 16 Introduction to JavaScript 3

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

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: http://people.cs.uchicago.edu/~hai/hw6/accessobject.html Introduction to JavaScript 3

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

Introduction to JavaScript 3

Introduction to JavaScript 3 Logical Operators Examples: BooleanVariables.html LogicalExamples.html Introduction to JavaScript 3

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

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

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

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

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

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

Expressions and Operators Example: StringExamples.html Introduction to JavaScript 3

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

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

Decision Making Statements if statements if…else statements Nested if statements switch statements Introduction to JavaScript 3

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

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

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

Introduction to JavaScript 3

Introduction to JavaScript 3

Introduction to JavaScript 3

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

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

Introduction to JavaScript 3

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

Introduction to JavaScript 3

Introduction to JavaScript 3

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

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

Introduction to JavaScript 3

Repetition Statements while statements do…while statements for statements break/continue statements Introduction to JavaScript 3

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

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

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

Introduction to JavaScript 3

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

Introduction to JavaScript 3

Introduction to JavaScript 3 Repetition while Statements Example: var count = 1; while (count <= 100) { document.writeln(count); count *= 2; } Introduction to JavaScript 3

Introduction to JavaScript 3

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

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

Introduction to JavaScript 3

Introduction to JavaScript 3

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

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

Introduction to JavaScript 3

Introduction to JavaScript 3

Introduction to JavaScript 3

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

Introduction to JavaScript 3

Introduction to JavaScript 3

Introduction to JavaScript 3

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

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

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

Introduction to JavaScript 3

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

Introduction to JavaScript 3

Introduction to JavaScript 3

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

Introduction to JavaScript 3 Using Events Example: ChangedValue.html Introduction to JavaScript 3

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

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

Introduction to JavaScript 3

Introduction to JavaScript 3

Introduction to JavaScript 3 Using Events More examples: warnuser.html confirmLinks.html Introduction to JavaScript 3

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

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

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

Introduction to JavaScript 3 Using Events Examples: testStatusBar.html CorrectStatus.html BodyParts.html Introduction to JavaScript 3

A Simple Image Rollover http://people.cs.uchicago.edu/~hai/hw6/imagerollover.html <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

More Effective Image Rollover http://people.cs.uchicago.edu/~hai/hw6/betterimagerollover.html <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

Using Events with Image Maps Examples: ShowCountry.html Changing images with MouseOver and MouseOut events. Introduction to JavaScript 3

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

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

Introduction to JavaScript 3 Using Events More examples: ImageOver.html ShowAnimal.html ShowAnimal2.html (uses functions) FamilyImageMap.html Introduction to JavaScript 3

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

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

Introduction to JavaScript 3

Introduction to JavaScript 3 The Location Object Example: location.href = “http://www.uchicago.edu Will cause the browser to open the uchicago home page Introduction to JavaScript 3

Introduction to JavaScript 3

Introduction to JavaScript 3 The Location Object The assign() method is same as the href property: location.assign(“http://www.uchicago.edu”) 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

Introduction to JavaScript 3 The Location Object The replace() method is similar to the href property: location.assign(“http://www.uchicago.edu) 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

Introduction to JavaScript 3 The Location Object Example: Redirect.html Redirect2.html Introduction to JavaScript 3

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

Introduction to JavaScript 3

Working with the History Object The History Object Example: http://www.comptechdoc.org/independent/web/cgi/javamanual/javahistory.html Introduction to JavaScript 3

Working with the Navigator Objects Used to obtain information about the current web browser Typically used to identify browser Introduction to JavaScript 3

Introduction to JavaScript 3

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

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 e-mail form data Introduction to JavaScript 3

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

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

The form array contains all forms in the document The elements[ ] array contains all the elements used in the form. Introduction to JavaScript 3

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

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

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

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

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

Introduction to JavaScript 3

Introduction to JavaScript 3

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