Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript Chapter 4. Topic to be covered.. What is JavaScript? What is JavaScript? Simple Program: Displaying a Line of Text in a Web Page Simple Program:

Similar presentations


Presentation on theme: "JavaScript Chapter 4. Topic to be covered.. What is JavaScript? What is JavaScript? Simple Program: Displaying a Line of Text in a Web Page Simple Program:"— Presentation transcript:

1 JavaScript Chapter 4

2 Topic to be covered.. What is JavaScript? What is JavaScript? Simple Program: Displaying a Line of Text in a Web Page Simple Program: Displaying a Line of Text in a Web Page Variables Variables Screen Output & Keyboard Input Screen Output & Keyboard Input Data types Data types Assignment Assignment Expression Expression Operators Operators Conditional Statement Conditional Statement

3 What is JavaScript?  Originally developed by Netscape, as LiveScript  Became a joint venture of Netscape and Sun in 1995, renamed JavaScript  Now standardized by the European Computer Manufacturers Association as ECMA-262 (also ISO 16262).  JavaScript Scripting language that facilitates a disciplined approach to designing computer programs that enhance the functionality and appearance of web pages. 3

4 JavaScript (3) Client runs JavaScript (client-side scripting) (1) HTTP Request HTTP Response (2) HTML file with embedded JavaScript

5  JavaScript is seldom used to write complete “programs” Instead, small bits of JavaScript are used to add functionality to HTML pages JavaScript is often used in conjunction with HTML “forms”  JavaScript is reasonably platform-independent

6 Common Uses of JavaScript  Display a message box  Select list navigation  Edit and validate form information  Create a new window with a specified size and screen position  Image Rollovers  Status Messages  Display Current Date  Calculations 6

7 7 Simple Program: Displaying a Line of Text in a Web Page  Spacing displayed by a browser in a web page is determined by the XHTML elements used to format the page  Often, JavaScripts appear in the section of the XHTML document  The browser interprets the contents of the section first  The tag indicates to the browser that the text that follows is part of a script. Attribute type specifies the scripting language used in the script—such as text/javascript

8 Simple Program: Displaying a Line of Text in a Web Page (cont)  - Either directly, as in -- JavaScript script – or -- JavaScript script –  - Or indirectly, as a file specified in the src attribute of, as in <script type = "text/javaScript" src = "myScript.js">

9 9 Portability Tip Some browsers do not support the tags. If your document is to be rendered with such browsers, enclose the script code between these tags in an XHTML comment, so that the script text does not get displayed as part of the web page. The closing comment tag of the XHTML comment ( --> ) is preceded by a JavaScript comment ( // ) to prevent the browser from trying to interpret the XHTML comment as a JavaScript statement.

10 10 Simple Program: Displaying a Line of Text in a Web Page (Cont.)  A string of characters can be contained between double ( " ) or single ( ' ) quotation marks  A string is sometimes called a character string, a message or a string literal  Comments are as in C or Java: Between // and the end of the line Between /* and */

11 11 Simple Program: Displaying a Line of Text in a Web Page (Cont.)  The parentheses following the name of a method contain the arguments that the method requires to perform its task (or its action)  Every statement should end with a semicolon (also known as the statement terminator), although none is required by JavaScript  JavaScript is case sensitive Not using the proper uppercase and lowercase letters is a syntax error

12 12 Simple Program: Displaying a Line of Text in a Web Page (Cont.)  Browser’s document object represents the XHTML document currently being displayed in the browser Allows a script programmer to specify XHTML text to be displayed in the XHTML document  Browser contains a complete set of objects that allow script programmers to access and manipulate every element of an XHTML document  Object Resides in the computer’s memory and contains information used by the script The term object normally implies that attributes (data) and behaviors (methods) are associated with the object An object’s methods use the attributes’ data to perform useful actions for the client of the object—the script that calls the methods

13 13 Simple Program: Displaying a Line of Text in a Web Page (Cont.)  The document object’s writeln method Writes a line of XHTML text in the XHTML document Text displayed is dependent on the contents of the string written, which is subsequently rendered by the browser. Browser will interpret the XHTML elements as it normally does to render the final text in the document

14 14 Displaying a line of text. Script begins Specifies that we are using the JavaScript language Writes an h1 welcome message in the XHTML document Prevents older browsers that do not support scripting from displaying the text of the script XHTML comment delimiter, commented for correct interpretation by all browsers Script ends

15 15 Modifying Our First Program  Method write displays a string like writeln, but does not position the output cursor in the XHTML document at the beginning of the next line after writing its argument

16 16 Modifying Our First Program (Cont.)  You cannot split a statement in the middle of a string. The + operator (called the “concatenation operator” when used in this manner) joins two strings together

17 17 Printing one line with separate stateme nts. Two write statements create one line of XHTML text Concatenation operator joins the string together, as it is split into multiple lines

18 18 Modifying Our First Program (Cont.)  A single statement can cause the browser to display multiple lines by using line-break XHTML tags ( ) throughout the string of XHTML text in a write or writeln method call

19 19 Printing on multiple lines with a single statement.

20 20 Inserts line-break

21 Checkpoint 1. Netscape's original name for JavaScript was ____________. 2. A standardized version of JavaScript is called____________. 3. The ____________ tag allows JavaScript to be inserted into an HTML/XHTML document. 4. JavaScript is mainly used for ____________ scripting. 5. _______________is used to denote a single-line comment and ____________ is used to denote a multi-line comment. 6. Every statement should end with a __________________. 21

22 Write a script that displays the numbers 1 to 4 on the same line, with each pair of adjacentnumbers separated by one space. Write the program using the following methods: a) Using document.writeln statement. ANS: document.writeln( "1 2 3 4" ); b) Using document.write statements. ANS: document.write( "1 " ); document.write( "2 " ); document.write( "3 " ); document.write( "4" ); or document.write( “1 2 3 4" );

23 Variable  A variable is a placeholder for information.  The variable is stored in the computer’s memory (RAM).  Variables are declared with a var statement: Variables names must begin with a letter or underscore Comprise of sequence of letters, numbers, _, Variable names are case-sensitive Eg. NAME, name, a, A, cs_170 Variables are untyped (they can hold values of any type) 23

24 Variable declaration – declaring use State variables to be used var statement var a; Declaration precedes variable usage in program var a; a = 5; document.write(a); var userName = "Karen"; document.write(userName);

25 Variable declaration – declaring use  More than one variable can be declared in a statement. var a, b;  Is the same as… var a; var b;  The order of variable declaration does not matter. var a, b, c;  Is the same as… var b, a, c;

26 Reserved words – can not be used as variable.

27 Calling Variable var address="22D Station St. Athens Ohio 45701 USA"; document.write(address);

28 Output…

29 Using Semicolon var x = "Welcome My Friends!"; var y = "It's a good habit adding semicolon in your script!"; document.write(x + " " + y);

30 Output

31 The JavaScript model for the HTML document is the Document object. The Document object has a method, write and writeln which dynamically creates content e.g., document.write("Answer: " + result + " "); Screen Output & Keyboard Input

32 Screen Output & Keyboard Input (cont)  The model for the browser display window is the Window object The Window object has three methods for creating dialog boxes: 1. Alert 2. Confirm 3. Prompt  Dialogs Useful to display information in windows that “pop up” on the screen to grab the user’s attention Typically used to display important messages to the user browsing the web page

33 Browser’s window object uses method alert to display an alert dialog Method alert requires as its argument the string to be displayed. Opens a dialog box which displays the parameter string and an OK button It waits for the user to press the OK button window.alert(“The sum is: 42"); Alert Box

34 Confirm Box Opens a dialog box and displays the parameter and two buttons, OK and Cancel Returns a Boolean value, depending on which button was pressed (it waits for one) window.confirm("Do you want to continue this download?");

35 Prompt Box The window object’s prompt method displays a dialog into which the user can type a value. The first argument is a message (called a prompt) that directs the user to take a specific action. The optional second argument is the default string to display in the text field. window.prompt("What is your name?", "");

36 Checkpoint: Write a statement to accomplish each of the following tasks: 1. Prompt the user to enter the first value, read the value from the user and store it in the variable xVal. ANS: xVal = window.prompt( "Enter first integer:", "0" ); 2.Prompt the user to enter the second value, read the value from the user and store it in the variable yVal. ANS: yVal = window.prompt( "Enter second integer:", "0" ); 3.Prompt the user to enter the third value, read the value from the user and store it in the variable zVal. ANS: zVal = window.prompt( "Enter third integer:", "0" ); 4.Convert xVal to an integer, and store the result in the variable x. ANS: x = parseInt( xVal ); 5.Convert yVal to an integer, and store the result in the variable y. ANS: y = parseInt( yVal ); 6.Convert zVal to an integer, and store the result in the variable z. ANS: z = parseInt( zVal );

37 Primitive / data types Strings Numbers – numeric literals Booleans – True and False Undefined - undefined Null - null

38 Strings Sequence of characters Eg. “CS_170” Use single quotes ‘ ’ or double “ ” Eg. var name; name = “katty”; Double quoted strings can contain single quotes and vice versa. eg. ‘ “We can leave now”, she said.’ Or “CS 170’s assignment”

39 Assignment statement Variable : declared variable Assignment symbol : notation for assign. operation (the equal to sign) Expression : tell comp how to compute new value Eg. var Area; Area = pi * r * r;

40 Essential points about assign. All three components required Value on RHS assigned to variable on LHS Value of variable on right is the value of variable at the start of the execution of assignment Eg. final = 0; final = final + 5; The value on LHS will be 5 while RHS will be 0.

41 Operators & Expressions o Arithmetic / * + - % o Relational = o Logical AND OR NOT o Unary, Binary operators.

42 Arithmetic operators Symbols of basic arithmetic

43 var two = 2; var ten = 10; var linebreak = " “; document.write("two plus ten = "); result = two + ten; document.write(result); document.write(linebreak); document.write("ten * ten = "); result = ten * ten; document.write(result); document.write(linebreak); document.write("ten / two = "); result = ten / two; document.write(result);

44 Output

45 Relational Operators Make comparison between two values Returns Boolean value - either true or false a < b Is a less than b a <= b Is a less than or equal to b a == b Is a equal to b a != b Is a not equal to b a >= b Is a greater than or equal to b a > b Is a greater than b Eg. salary > 1000 age >= 18 course == cs170

46 Logical Operators test two or more relationships together AND OR NOT

47 Logical AND operator && exp1 && exp 2 outcome is true if the outcome for both exp1 and exp2 are true course == cs170 and semester <8 in JavaScript course == cs170 && semester <8

48 Logical OR operator || exp1 || exp 2 outcome is true if the outcome for either exp1 and exp2 are true level 3 || level 6

49 Logical NOT operator ! Unary operator !(expression) Outcome is the opposite of the value of operand !(marks = 5) True for 4

50 Unary/binary operators All of the below are binary operators a*b, a+b, a/b, a-b a and b are known as operands Unary operators involve one operand Eg. (-) -a, -4

51 - Similar to C, Java, and C++ -Compound statements are delimited by braces { } (Group a number of statements together and execute like a single statement) 1. Primitive values - If it is a string, it is true unless it is empty or "0" - If it is a number, it is true unless it is zero 2. Relational Expressions - The usual six: ==, !=,, = 3. Compound Expressions - The usual operators: &&, ||, and ! Control Statements

52 Control Statements (continued) if (condition) { … commands to execute if condition is true } else { … commands to execute if condition is false } 4. if..else

53 var age = prompt("Please enter your age : ",""); if (age < 18) { alert("Under 18, No Smoking!"); } else { alert("Smoking is no good for your health!"); }

54 Control Statements (continued) 5. Switch switch (expression) { case value_1: // value_1 statements case value_2: // value_2 statements … [default: // default statements] } - The statements can be either statement sequences or compound statements

55 6. Loop statements while ( control_expression ) statement or compound for ( init ; control ; increment ) statement or compound - init can have declarations, but the scope of such variables is the whole script do statement or compound while ( control_expression ) Control Statements (continued)

56 An array is a special variable, which can hold more than one value, at a time. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: cars1=“Proton"; cars2="Volvo"; cars3="BMW"; An array can hold all your variable values under a single name. And you can access the values by referring to the array name. Each element in the array has its own ID so that it can be easily accessed. Arrays

57 An array can be defined in three ways. The following code creates an Array object called myCars: 1.var myCars=new Array(); // regular array myCars[0]=“Proton"; // argument to control array's size) myCars[1]="Volvo"; myCars[2]="BMW"; 2. var myCars=new Array(“Proton","Volvo","BMW"); // condensed array 3. var myCars=[“Proton","Volvo","BMW"]; // literal array Create an Array

58 Access an Array  You can refer to a particular element in an array by referring to the name of the array and the index number.  The index number starts at 0.  The following code line: document.write(myCars[0]);// will result in the following output: Proton  Modify Values in an Array  To modify a value in an existing array, just add a new value to the array with a specified index number: myCars[0]="Opel"; document.write(myCars[0]); // will result in the following output: Opel

59 Function  A function is a block of one or more JavaScript statements with a specific purpose, which can be run when needed. function function_name() {... JavaScript statements … } 59

60 Using Functions function showAlert() { alert("Please click OK to continue."); } 60 //Calling the Function showAlert(); //Defining the Function

61 61 JavaScript: Objects

62 Document Object Model (DOM)  A portion of the DOM is shown at the left.  Defines every object and element on a web page  Hierarchical structure  Accesses page elements and apply styles to page elements 62

63 Object  An object is a thing or entity. Browser window Submit button Web page document 63

64 Property  A property is a characteristic or attribute of an object. The background color of a web page document document.bgcolor The date the web page file was last modified document.lastmodified The src file of an image object image1.src 64

65 Method  A method is an action (a verb) Writing text to a web page document document.write() Submitting a form form1.submit() 65

66 66 Introduction to Object Technology JavaScript uses objects to perform many tasks It is referred to as an object-based programming language  Objects have attributes and exhibit behaviors

67 67 Introduction to Object Technology (Cont.)  Objects have the property of information hiding Objects may know how to communicate with one another across well-defined interfaces, but normally they are not allowed to know how other objects are implemented  Web browsers Contain a set of objects that encapsulate an XHTML document’s elements The objects expose to a JavaScript programmer the attributes and behaviors that enable a JavaScript program to interact with (or script) those elements (objects)

68 68 Introduction to Object Technology (Cont.) An object’s methods are called by writing the name of the object followed by a dot operator (. ) and the name of the method  In parentheses following the method name is the argument (or a comma-separated list of arguments) to the method

69 69 Math object methods.

70 70 Properties of the Math object.

71 71 Some String object method s (Part 1 of 2).

72 72 Some String object method s (Part 2 of 2).

73 73 Date object method s (Part 1 of 2).

74 74 Date object method s (Part 2 of 2).

75 75 Boolean object methods.

76 76 Number object method s and properti es.

77 77 Important document object methods and properties.

78 78 Importa nt window object method s and properti es.

79 79 Events and Event Handling

80 JavaScript and Events  Events: actions taken by the Web page visitor clicking (onclick), placing the mouse on an element (onmouseover), removing the mouse from an element (onmouseout), loading the page (onload), unloading the page (onunload), etc. 80

81 Events EventEvent Handler click onclick load onload mouseover onmouseover mouseout onmouseout submit onsubmit unload onunload 81

82 JavaScript and Events  JavaScript can be configured to perform actions when events occur. The event name is coded as an attribute of an XHTML tag The value of the event attribute contains the JavaScript code Example: Display an alert box when the mouse is placed over a hyperlink. 82 Home

83 83 Introduction  JavaScript events allow scripts to respond to user interactions and modify the page accordingly  Events and event handling help make web applications more responsive, dynamic and interactive  The process of connecting an event handler to an event is called registration

84 84 Cross-browser events. (Part 1 of 2.)

85 85 Cross-browser events. (Part 2 of 2.)

86 Dynamic HTML (DHTML)  Use DHTML to create interesting and complex visual effects.  DHTML technology integrates JavaScript, CSS and HTML to create striking effects that are not otherwise possible.

87 Examples of DHTML  Positioning Elements  Moving Elements  Element Visibility  Changing Colors and Fonts  Dynamic Content  Stacking Elements  Locating the Mouse Cursor  Reacting to a Mouse Click  Slow Movement of Elements  Dragging and Dropping an Element

88 Display of mover.html (before pressing the Move It button)

89 Display of mover.html (after pressing the Move It button)

90 Display of dynLink.html with the cursor not over the link

91 Display of dynLink.html with the mouse cursor over the link

92 JavaScript Debugging(1)  Check the syntax of the statements Pay very close attention to upper and lower case letters, spaces, and quotations  Verify that you have saved the page with your most recent changes  Verify that you are testing the most recent version of the page (refresh or reload the page)  If you get an error message, use the error messages that are displayed by the browser In Firefox: Select Tools >Web Developer> Error Console 92

93 JavaScript Debugging(2)  Use the Firefox browser: Select Tools > Error Console from the Menu  The Error Console will indicate an issue and the line number  This may not be exactly where the problem is  Sometimes the error is a one or two lines above the indicated line number. 93

94 JavaScript & Accessibility  Don’t expect JavaScript to always function for every visitor Some may have JavaScript disabled Some may be physically unable to click a mouse  Provide a way for your site to be used if JavaScript is not functioning Plain text links E-mail contact info 94

95 JavaScript Resources  JavaScript Tutorials http://www.w3schools.com/JS http://www.w3schools.com/JS  JavaScript Tutorial for the Total Non-Programmer http://www.webteacher.com/javascript/ http://www.webteacher.com/javascript/  More Beginning JavaScript Tutorials http://echoecho.com/javascript.htm http://echoecho.com/javascript.htm  Core JavaScript 1.5 Reference Manual http://www.webreference.com/javascript/reference/core_re f http://www.webreference.com/javascript/reference/core_re f  Creating Accessible JavaScript http://www.webaim.org/techniques/javascript http://www.webaim.org/techniques/javascript 95


Download ppt "JavaScript Chapter 4. Topic to be covered.. What is JavaScript? What is JavaScript? Simple Program: Displaying a Line of Text in a Web Page Simple Program:"

Similar presentations


Ads by Google