1 cs 21a beginning javascript programming introduction to javascript programming sonny huang

93
1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

Upload: jeffrey-wade

Post on 26-Dec-2015

228 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

1

CS 21A • Beginning JavaScript

Programming

Introduction to JavaScript Programming

Sonny Huang

Page 2: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

2

Introduction to JavaScript Programming

Outline       Describe JavaScript       Define HTML and explain the use of HTML tags       Define attribute       Differentiate between JavaScript and VBScript       Define JavaScript cookies and variables       Define string, numeric, and Boolean JavaScript variable types       Discuss the rules for naming variables       Differentiate between variables and literals       Discuss special codes and how they are used in a literal       Discuss the advantages and disadvantages of using JavaScript       Define expression and describe the arithmetic operators

Page 3: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

3

Introduction to JavaScript Programming

Outline       Discuss the order of precedence in an expression       Define concatenation       Define conditionals and the use of If and While statements       Discuss the use of JavaScript functions       Discuss If, If . . . Else, and While statements and loops       Define objects, properties, methods, and events       Describe how event handlers and forms are used       Define frames and arrays

Page 4: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

4

Introduction

Introduction JavaScript• A scripting language developed by Netscape and Sun

Microsystems to enable Web authors to design interactive sites.

• Although it shares many of the features and structures of the full Java language, it was developed independently.

• JavaScript can interact with HTML source code, enabling Web authors to spice up their sites with dynamic content.

Page 5: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

5

Introduction

• JavaScript is endorsed by a number of software companies and is an open language that anyone can use without purchasing a license.

• It is supported by recent browsers from Netscape and Microsoft, though Internet Explorer supports only a subset, which Microsoft calls Jscript.

Page 6: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

6

Introduction

• Using Java Script, you can enhance a Web page by adding items such as:

• Scrolling message• Animations and dynamic images• Data input forms• Pop-up windows• Interactive quizzes

Page 7: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

7

Introduction

HTML• Short for HyperText Markup Language, the authoring

language used to create documents on the World Wide Web.

• HTML defines the structure and layout of a Web document by using a variety of tags and attributes.

• The correct structure for an HTML document starts with <HTML><HEAD>(enter here what document is about)</HEAD><BODY> and ends with </BODY></HTML>. All the information you'd like to include in your Web page fits in between the <BODY> and </BODY> tags.

Page 8: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

8

Introduction

• There are hundreds of other tags used to format and layout the information in a Web page.

• For instance, <P> is used to make paragraphs and <I> … </I>is used to italicize fonts.

• Tags are also used to specify hypertext links. These allow Web developers to direct users to other Web pages with only a click of the mouse on either an image or word(s).

Page 9: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

9

Introduction

Java• A high-level programming language developed by Sun

Microsystems.

• Java was originally called OAK, and was designed for handheld devices and set-top boxes.

• Oak was unsuccessful so in 1995 Sun changed the name to Java and modified the language to take advantage of the burgeoning World Wide Web.

• Java is an object-oriented language similar to C++, but simplified to eliminate language features that cause common programming errors.

Page 10: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

10

Introduction

• Java source code files (files with a .java extension) are compiled into a format called bytecode (files with a .class extension), which can then be executed by a Java interpreter.

• Compiled Java code can run on most computers because Java interpreters and runtime environments, known as Java Virtual Machines (VMs), exist for most operating systems, including UNIX, the Macintosh OS, and Windows.

• Bytecode can also be converted directly into machine language instructions by a just-in-time compiler (JIT).

Page 11: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

11

Introduction

• Java is a general purpose programming language with a number of features that make the language well suited for use on the World Wide Web.

• Small Java applications are called Java applets and can be downloaded from a Web server and run on your computer by a Java-compatible Web browser, such as Netscape Navigator or Microsoft Internet Explorer.

Page 12: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

12

Introduction • JavaScript compared to Java JavaScript Java

JavaScript Java

Interpreted (not compiled) by client. Compiled bytecodes downloaded from server, executed on client.

Object-based. No distinction between types of objects. Inheritance is through the prototype mechanism and properties and methods can be added to any object dynamically.

Object-oriented. Objects are divided into classes and instances with all inheritance through the class hieararchy. Classes and instances cannot have properties or methods added dynamically.

Code integrated with, and embedded in, HTML.

Applets distinct from HTML (accessed from HTML pages).

Variable data types not declared (loose typing).

Variable data types must be declared (strong typing).

Dynamic binding. Object references checked at runtime.

Static binding. Object references must exist at compile-time.

Cannot automatically write to hard disk. Cannot automatically write to hard disk.

Page 13: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

13

Introduction

C• A high-level programming language developed by

Dennis Ritchie at Bell Labs in the mid 1970s.

• Although originally designed as a systems programming language, C has proved to be a powerful and flexible language that can be used for a variety of applications, from business programs to engineering.

• C is a particularly popular language for personal computer programmers because it is relatively small -- it requires less memory than other languages.

Page 14: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

14

Introduction

• The first major program written in C was the UNIX operating system, and for many years C was considered to be inextricably linked with UNIX. Now, however, C is an important language independent of UNIX.

• Although it is a high-level language, C is much closer to assembly language than are most other high-level languages.

• This closeness to the underlying machine language allows C programmers to write very efficient code.

• The low-level nature of C, however, can make the language difficult to use for some types of applications.

Page 15: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

15

Introduction

Compiler• A program that translates source code into object code.

• The compiler derives its name from the way it works, looking at the entire piece of source code and collecting and reorganizing the instructions.

• Compilers require some time before an executable program emerges. However, programs produced by compilers run much faster than the same programs executed by an interpreter.

• Every high-level programming language (except strictly interpretive languages) comes with a compiler.

Page 16: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

16

Introduction

Interpreter• An interpreter translates high-level instructions into an

intermediate form, which it then executes.

• In contrast, a compiler translates high-level instructions directly into machine language.

• The advantage of an interpreter is that it does not need to go through the compilation stage during which machine instructions are generated. This process can be time-consuming if the program is long.

Page 17: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

17

Introduction

• The interpreter can immediately execute high-level programs. For this reason, interpreters are sometimes used during the development of a program, when a programmer wants to add small sections at a time and test them quickly. In addition, interpreters are often used in education because they allow students to program interactively.

• Interpreters are available for most high-level languages. However, BASIC and LISP are especially designed to be executed by an interpreter.

Page 18: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

18

Introduction

JavaScript• Is similar to the C programming language in appearance and

style.

• Variable and statements are case sensitive. Most of the statements are using lowercase, but, the event handlers, and many of the objects, properties, and methods use a mixed-case spelling. Some old browsers have problem with mix-case.

• Is an interpreted language. There is no executable file exist.

• Only run on JavaScript interpreter built into browsers. The version of JavaScript used depends on the version of browser

Page 19: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

19

HTML Tags

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html40/strict.dtd">

<HTML> <HEAD> <META name="Author" content="Dave Raggett">

<TITLE>My first HTML document</TITLE> </HEAD> <BODY> <P>Hello world! </BODY>

</HTML>

Page 20: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

20

HTML TagsThe HEAD element contains information about the current document, such as its title, keywords that may be useful to search engines, and other data that is not considered document content.

Every HTML document must have a TITLE element in the HEAD section. TITLE element to identify the contents of a document.

The META element can be used to identify properties of a document (e.g., author, expiration date, a list of key words, etc.) and assign values to those properties. This specification does not define a normative set of properties.

Each META element specifies a property/value pair. The name attribute identifies the property and the content attribute specifies the property's value.

Page 21: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

21

HTML Tags

The BODY of a document contains the document's content. The content may be presented by a user agent in a variety of ways. For example, for visual browsers, you can think of the body as a canvas where the content appears: text, images, colors, graphics, etc.

• TEXT for color of the text• BACKGROUND uses .gif as background of the html

page• In HTML tags are in pairs

Page 22: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

22

HTML Tags

• INPUT tag for a text box in a FORM for data entry.• Type, Name, Value, and Size are all attributes of the

INPUT tag.• Type = “text” indicates that a text box is created.• Name = “PhoneNumber” assigns

variable(PhoneNumber) or name to the text box. This variable will store a data entered.

• Value will store the initial value to the Type which is text box.

• Size=17 indicates the size, which is in characters, of the text box.

Page 23: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

23

HTML Tags

More about HTML documentation at webhttp://www.w3.org/TR/REC-html40/

Page 24: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

24

SCRIPT Tags

The <SCRIPT> tag is an extension to HTML that can enclose any number of JavaScript statements as shown here and usually placed at the HEAD section of the HTML:

<SCRIPT>   JavaScript statements...</SCRIPT>

A document can have multiple <SCRIPT> tags, and each can enclose any number of JavaScript statements.

Page 25: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

25

SCRIPT Tags

Specifying the JavaScript Version

As JavaScript evolves along with Navigator, its capabilities expand greatly. This means that JavaScript written for Navigator 4.0 may not work in earlier versions of Navigator. To ensure that users of earlier versions of Navigator avoid problems when viewing pages that use JavaScript 1.2, use the LANGUAGE attribute in the <SCRIPT> tag to indicate which version of JavaScript you're using.

Page 26: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

26

SCRIPT Tags

By using the LANGUAGE attribute, you can write general JavaScript that Navigator version 2.0 and higher recognize, and include additional or refined behavior for newer versions of Navigator.

Statements within a <SCRIPT> tag are ignored if the browser does not have the level of JavaScript support specified in the LANGUAGE attribute.

for example: Navigator 2.0 executes code within the <SCRIPT LANGUAGE="JavaScript"> tag; it ignores code within the <SCRIPT LANGUAGE="JavaScript1.1"> and <SCRIPT LANGUAGE="JavaScript1.2"> tags.

Page 27: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

27

SCRIPT Tags

Navigator 3.0 executes code within the <SCRIPT LANGUAGE="JavaScript"> and <SCRIPT LANGUAGE="JavaScript1.1"> tags; it ignores code within the <SCRIPT LANGUAGE="JavaScript1.2"> tag.

Navigator 4.0 executes code within the <SCRIPT LANGUAGE="JavaScript">, <SCRIPT LANGUAGE="JavaScript1.1">, and <SCRIPT LANGUAGE="JavaScript1.2"> tags.

Page 28: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

28

SCRIPT Tags

This example shows how to define functions three times, once for JavaScript 1.0, once using JavaScript 1.1 features, and a third time using JavaScript 1.2 features.

<SCRIPT LANGUAGE="JavaScript">// Define 1.0-compatible functions such as doClick() here</SCRIPT>

<SCRIPT LANGUAGE="JavaScript1.1">// Redefine those functions using 1.1 features// Also define 1.1-only functions</SCRIPT>

<SCRIPT LANGUAGE="JavaScript1.2">// Redefine those functions using 1.2 features// Also define 1.2-only functions</SCRIPT>

Page 29: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

29

SCRIPT Tags

Hiding Scripts within Comment Tags

Only Netscape Navigator versions 2.0 and later recognize JavaScript. To ensure that other browsers ignore JavaScript code, place the entire script within HTML comment tags, and precede the ending comment tag with a double-slash (//) that indicates a JavaScript single-line comment:

Page 30: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

30

SCRIPT Tags

A simple script

Hello, net!That's all, folks.

You may sometimes see a semicolon at the end of each line of JavaScript. In general, semicolons are optional and are required only if you want to put more than one statement on a single line.

Page 31: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

31

SCRIPT Tags

Specifying a File of JavaScript CodeThe SRC attribute of the <SCRIPT> tag lets you specify a file as the JavaScript source (rather than embedding the JavaScript in the HTML). For example:

<HEAD><TITLE>My Page</TITLE><SCRIPT SRC="common.js">...</SCRIPT></HEAD><BODY>

This attribute is especially useful for sharing functions among many different pages.

Page 32: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

32

SCRIPT Tags

The closing </SCRIPT> tag is required.

JavaScript statements within a <SCRIPT> tag with a SRC attribute are ignored unless the inclusion has an error.

For example, you might want to put the following statement between the <SCRIPT SRC="..."> and </SCRIPT> statements: document.write("Included JS file not found");The SRC attribute can specify any URL, relative or absolute.

For example: <SCRIPT SRC="http://home.netscape.com/functions/jsfuncs.js“ > External JavaScript files cannot contain any HTML tags: they must contain only JavaScript statements and function definitions.

Page 33: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

33

SCRIPT Tags

External JavaScript files should have the file name suffix .js, and the server must map the .js suffix to the MIME type application/x-javascript, which the server sends back in the HTTP header.

To map the suffix to the MIME type, add the following line to the mime.types file in the server's config directory, and then restart the server.

type=application/x-javascript   exts=jsIf the server does not map the .js suffix to the application/x-javascript MIME type, Navigator improperly loads the JavaScript file specified by the SRC attribute.

NOTE: This requirement does not apply if you use local files.

Page 34: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

34

VBScript

• Short for Visual Basic Scripting Edition

• a scripting language developed by Microsoft and supported by Microsoft's Internet Explorer Web browser.

• VBScript is based on the Visual Basic programming language, but is much simpler.

• In many ways, it is similar to JavaScript. It enables Web authors to include interactive controls, such as buttons and scrollbars, on their Web pages.

Page 35: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

35

Cookies

• A message given to a Web browser by a Web server.

• The browser stores the message in a text file(Navigator- cookies.txt, IE - Cookies folder).

• The message is then sent back to the server each time the browser requests a page from the server.

• The main purpose of cookies is to identify users and possibly prepare customized Web pages for them.

• When you enter a Web site using cookies, you may be asked to fill out a form providing such information as your name and interests. This information is packaged into a cookie and sent to your Web browser which stores it for later use.

Page 36: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

36

Cookies

• The next time you go to the same Web site, your browser will send the cookie to the Web server. The server can use this information to present you with custom Web pages. So, for example, instead of seeing just a generic welcome page you might see a welcome page with your name on it.

• The name cookie derives from UNIX objects called magic

cookies. These are tokens that are attached to a user or program and change depending on the areas entered by the user or program

Page 37: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

37

Cookies

• Each cookie is a small item of information with an optional expiration date and is added to the cookie file in the following format: name=value;expires=expDate;

name is the name of the datum being stored, and value is its value.

• If name and value contain any semicolon, comma, or blank (space) characters, you must use the escape function to encode them and the unescape function to decode them.

• expDate is the expiration date, in GMT date format:

Page 38: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

38

Cookies

• The expiration date is an optional parameter indicating how long to maintain the cookie.

• If expDate is not specified, the cookie expires when the user exits the current Navigator session.

• Navigator maintains and retrieves a cookie only if its expiration date has not yet passed.

• JavaScript cookies cannot get data from the user’s hard drive, read e-mail, or steal other sensitive information.

• Web sites can limited an access if the cookies info. is blocked.

Page 39: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

39

JavaScript Basic – Variables, Literals, and expressions

• You use variables as symbolic names for values in your application.

• You give variables names by which you refer to them and which must conform to certain rules.

1. A JavaScript identifier, or name, must start with a letter or underscore ("_");

2. subsequent characters can also be digits (0-9).3. Because JavaScript is case sensitive, letters

include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).

Page 40: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

40

JavaScript Basic – Variables, Literals, and expressions

• JavaScript is a loosely typed language. That means you do not have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution.

• for example, you could define a variable as follows: var answer = 42

• And later, you could assign the same variable a string value, for example, answer = "Thanks for all the fish..."Because JavaScript is loosely typed, this assignment does not cause an error message.

Page 41: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

41

JavaScript Basic – Variables, Literals, and expressions

LiteralYou use literals to represent values in JavaScript. These are fixed values, not variables, that you literally provide in your script.

Numeric literal.

String Literal; The maximum number of characters in a string is 255.

Page 42: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

42

JavaScript Basic – Variables, Literals, and expressions

Special code

“To be or not to be, that is the question!” Hamlet

Page 43: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

43

JavaScript Basic – Variables, Literals, and expressions

document.write(expression1 [,expression2], ...[,expressionN])

• The write method displays any number of expressions in a document window. You can specify any JavaScript expression with the write method, including numerics, strings, or logicals.

• The writeln method is the same as the write method, except the write method does not append a newline character to the end of the output.

• Use the write method within any <SCRIPT> tag or within an event handler.

Page 44: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

44

JavaScript Basic – Variables, Literals, and expressions

• Event handlers execute after the original document closes, so the write method will implicitly open a new document of mimeType text/html if you do not explicitly issue a document.open() method in the event handler.

• You can use the write method to generate HTML and JavaScript code. However, the HTML parser reads the generated code as it is being written, so you might have to escape some characters.

Page 45: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

45

JavaScript Basic – Variables, Literals, and expressions

• For example, the following write method generates a comment and writes it to window2:

window2=window.open('','window2')beginComment="\<!--"endComment="--\>"window2.document.write(beginComment)window2.document.write(" This some text inside a comment. ")window2.document.write(endComment)

Page 46: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

46

JavaScript Basic – Variables, Literals, and expressions

alert("message")

• Use the alert method to display a message that does not require a user decision. The message argument specifies a message that the dialog box contains.

• Although alert is a method of the window object, you do not need to specify a windowReference when you call it. For example, windowReference.alert() is unnecessary.

Page 47: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

47

JavaScript Basic – Variables, Literals, and expressions

function testValue(textElement) {   if (textElement.length > 8) {      alert("Please enter a name that is 8 characters or less")   }}

Page 48: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

48

JavaScript Basic – Variables, Literals, and expressions

Expressions and Operators• An expression is any valid set of literals, variables,

operators, and expressions that evaluates to a single value; the value can be a number, a string, or a logical value.

• Conceptually, there are two types of expressions: those that assign a value to a variable, and those that simply have a value. For example, the expression x = 7 is an expression that assigns x the value seven. This expression itself evaluates to seven. Such expressions use assignment operators.

Page 49: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

49

JavaScript Basic – Variables, Literals, and expressions

• other hand, the expression 3 + 4 simply evaluates to seven; it does not perform an assignment. The operators used in such expressions are referred to simply as operators.

JavaScript has the following types of expressions: • Arithmetic: evaluates to a number, for example

3.14159 • String: evaluates to a character string, for example,

"Fred" or "234" • Logical: evaluates to true or false

Page 50: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

50

JavaScript Basic – Variables, Literals, and expressions

shows an expression that is used in a simple math problem.

shows initializing a variable to zero.

Page 51: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

51

JavaScript Basic – Variables, Literals, and expressions

Arithmetic operatorsArithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

Page 52: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

52

JavaScript Basic – Variables, Literals, and expressions

Increment and decrement Operator

Page 53: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

53

JavaScript Basic – Variables, Literals, and expressions

Shorthanded expression

Page 54: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

54

JavaScript Basic – Variables, Literals, and expressions

Precedence: The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.

Page 55: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

55

JavaScript Basic – Variables, Literals, and expressions

Concatenationthe concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings. For example, "my " + "string" returns the string "my string".

The shorthand assignment operator += can also be used to concatenate strings. For example, if the variable mystring has the value "alpha," then the expression mystring += "bet" evaluates to "alphabet" and assigns this value to mystring

Page 56: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

56

JavaScript Basic – Variables, Literals, and expressions

The end result is that completeMsg now contains the contents of Message1 and Message2.

The older browsers have a limitation on how many characters you can place in a string.

Page 57: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

57

Conditionals

• JavaScript allows us to validate data while enter the information through a form.

• To validate data, we need to compare or test data entered to a desired value.

• This test is called a conditional, and the result of the test is either True or False.

• Conditionals are used in conjunction with If and While statement.

Page 58: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

58

Conditionals

Page 59: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

59

Conditionals

Conditional statementUse the if statement to perform certain statements if a logical condition is true; use the optional else clause to perform other statements if the condition is false. An if statement looks as follows:

if (condition) {          statements1 } else {          statements2 }

The condition can be any JavaScript expression that evaluates to true or false. The statements to be executed can be any JavaScript statements, including further nested if statements.

Page 60: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

60

Conditionals

If you want to use more than one statement after an if or else statement, you must enclose the statements in curly braces, {}.

Page 61: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

61

Conditionals

While LoopA while statement repeats a loop as long as a specified condition evaluates to true. A while statement looks as follows:

while (condition) {          statements}

If the condition becomes false, the statements within the loop stop executing and control passes to the statement following the loop.

Page 62: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

62

Conditionals

The condition test occurs only when the statements in the loop have been executed and the loop is about to be repeated. That is, the condition test is not continuous but is performed once at the beginning of the loop and again just following the last statement in statements, each time control passes through the loop.

Page 63: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

63

Functions

A function definition consists of the function keyword, followed by

• The name of the function. • A list of arguments to the function, enclosed

in parentheses and separated by commas. • The JavaScript statements that define the

function, enclosed in curly braces, { }. The statements in a function can include calls to other functions defined in the current application.

Page 64: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

64

Functions

A statement that declares a JavaScript function name with the specified parameters param. Acceptable parameters include strings, numbers, and objects.

To return a value, the function must have a return statement that specifies the value to return. You cannot nest a function statement in another statement or in itself.

Page 65: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

65

Functions

All parameters are passed to functions, by value. In other words, the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function.

function name([param] [, param] [..., param]) {   statements }

name is the function name. param is the name of an argument to be passed to the

function. A function can have up to 255 arguments.

Page 66: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

66

Functions

//This function returns the total dollar amount of sales, when//given the number of units sold of products a, b, and c.function calc_sales(units_a, units_b, units_c) {   return units_a*79 + units_b*129 + units_c*699}

Page 67: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

67

Objects, properties, and Methods

ObjectGenerally, any item that can be individually selected and manipulated.

This can include shapes and pictures that appear on a display screen as well as less tangible software entities.

In object-oriented programming, for example, an object is a self-contained entity that consists of both data and procedures to manipulate the data.

Page 68: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

68

Objects, properties, and Methods

OOP(object-oriented programming )type of programming in which programmers define not only the data type of a data structure, but also the types of operations (functions) that can be applied to the data structure.

In this way, the data structure becomes an object that includes both data and functions.

In addition, programmers can create relationships between one object and another.

For example, objects can inherit characteristics from other objects.

Page 69: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

69

Objects, properties, and Methods

One of the principal advantages of object-oriented programming techniques over procedural programming techniques is that they enable programmers to create modules that do not need to be changed when a new type of object is added.

A programmer can simply create a new object that inherits many of its features from existing objects. This makes object-oriented programs easier to modify.

Page 70: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

70

Objects, properties, and Methods

PropertiesA JavaScript object has properties associated with it. You access the properties of an object with a simple notation:

objectName.propertyNameBoth

the object name and property name are case sensitive.

You define a property by assigning it a value.

Page 71: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

71

Objects, properties, and Methods

For example, suppose there is an object named myCar (for now, just assume the object already exists). You can give it properties named make, model, and year as follows:

myCar.make = "Ford"myCar.model = "Mustang"myCar.year = 69;

Page 72: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

72

Objects, properties, and Methods

MethodA method is a function associated with an object.

defining a method the same way as we define a standard function.

Then we use the following syntax to associate the function with an existing object:

object.methodname = function_namewhere

object is an existing object, methodname is the name you are assigning to the method, and function_name is the name of the function.

Page 73: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

73

Objects, properties, and Methods

We can then call the method in the context of the object as follows:

object.methodname(params);

You can define methods for an object type by including a method definition in the object constructor function.

For example, you could define a function that would format and display the properties of the previously-defined car objects;

Page 74: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

74

Objects, properties, and Methods

for example, function displayCar() {          var result = "A Beautiful " + this.year +

“ “ + this.make                    + " " + this.model          pretty_print(result)}

where pretty_print is the function (defined in "Functions") to display a horizontal rule and a string. Notice the use of this to refer to the object to which the method belongs.

Page 75: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

75

Objects, properties, and Methods

We can make this function a method of car by adding the statement

this.displayCar = displayCar

to the object definition. So, the full definition of car would now look like

function car(make, model, year, owner) {          this.make = make          this.model = model          this.year = year          this.owner = owner          this.displayCar = displayCar}

Page 76: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

76

Objects, properties, and Methods

Then we can call the displayCar method for each of the objects as follows:

car1.displayCar()car2.displayCar()

Page 77: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

77

Objects, properties, and Methods

ArgumentIn programming, a value that you pass to a routine(method, function, or procedure).

For example, function car(make, model, year, owner), make, model, year owner are arguments. Argument is often used synonymously with parameter.

Arguments can be literals, or variables.

Page 78: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

78

Objects, properties, and Methods

Java Object hierarchy

Page 79: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

79

Objects, properties, and Methods

Java Object hierarchy

Page 80: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

80

Events

JavaScript applications in browsers are largely event-driven.

Events are actions that occur usually as a result of something the user does.

For example, clicking a button is an event, as is changing a text field or moving the mouse over a link.

For your script to react to an event, you define event handlers, such as onChange and onClick.

When an action associated with an event handler occurs, it is called triggering the event.

Page 81: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

81

Events

Event Applies to Occurs when Event handler

DragDrop

windows User drops an object onto the browser window, such as dropping a file on the browser window

onDragDrop

Error images, windows

The loading of a document or image causes an error

onError

Focus windows and all form elements

User gives input focus to window or form element

onFocus

KeyDown

documents, images, links, text areas

User depresses a key onKeyDown

KeyPress documents, images, links, text areas

User presses or holds down a key onKeyPress

Page 82: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

82

Events

Event Applies to Occurs when Event handler

KeyUp documents, images, links, text areas

User releases a key onKeyUp

Load document body

User loads the page in the Navigator

onLoad

MouseDown

documents, buttons, links

User depresses a mouse button onMouseDown

MouseMove

nothing by default

User moves the cursor onMouseMove

MouseOut areas, links User moves cursor out of a client-side image map or link

onMouseOut

MouseOver

links User moves cursor over a link onMouseOver

Page 83: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

83

Events

Event Applies to Occurs when Event handler

MouseUp documents, buttons, links

User releases a mouse button onMouseUp

Move windows User or script moves a window onMove

Reset forms User resets a form (clicks a Reset button)

onReset

Resize windows User or script resizes a window onResize

Select text fields, textareas

User selects form element's input field

onSelect

Submit forms User submits a form onSubmit

Unload document body

User exits the page onUnload

Page 84: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

84

Events

Forms

Form, lets users input text and make choices from Form elements such as checkboxes, radio buttons, and selection lists. You can also use a form to post data to a server.

Click on a button will change the background color to white.

Use the timeLine() function to check the system time to display different image.

Page 85: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

85

Events

Focus

•A focus event occurs when a window, frame, or frameset receives focus or when a form element receives input focus.

•The focus event can result from a focus method or from the user clicking the mouse on an object or window or tabbing with the keyboard.

•Selecting within a field results in a select event, not a focus event. The onFocus event handler executes JavaScript code when a focus event occurs.

Page 86: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

86

Events

Blur

A blur event occurs when a form element loses focus or when a window or frame loses focus.

The blur event can result from a blur method or from the user clicking the mouse on another object or window or tabbing with the keyboard.

The onBlur event handler executes JavaScript code when a blur event occurs.

Page 87: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

87

Events

For windows, frames, and framesets, the onBlur event handler specifies JavaScript code to execute when a window loses focus.

A frame's onBlur event handler overrides an onBlur event handler in the <BODY> tag of the document loaded into frame.

Page 88: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

88

Frames and Arrays

FrameA window that can display multiple, independently scrollable frames on a single screen, each with its own distinct URL.

Frames can point to different URLs and be targeted by other URLs, all within the same screen. A series of frames makes up a page.

HTML syntax To define a Frame object, use standard HTML syntax with the addition of JavaScript event handlers:

Page 89: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

89

Frames and Arrays

<FRAMESET   ROWS="rowHeightList"   COLS="columnWidthList"     <FRAME SRC="URL" NAME="frameName">   [ ... <FRAME SRC="URL" NAME="frameName">]</FRAMESET>

HTML attributes ROWS="rowHeightList" is a comma-separated list of

values specifying the row-height of the frame(pixels) COLS="columnWidthList" is a comma-separated list of

values specifying the column-width of the frame.

Page 90: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

90

Frames and Arrays

<FRAME> defines a frame.

SRC="URL" specifies the URL of the document to be displayed in the frame.

NAME="frameName" specifies a name to be used as a target of hyperlink jumps.

Page 91: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

91

Frames and Arrays

Arrays

JavaScript does not have an explicit array data type.

However, you can use the built-in Array object and its methods to work with arrays in your applications.

The Array object has methods for joining, reversing, and sorting arrays. It has a property for determining the array length.

An array is an ordered set of values that you reference through a name and an index.

Page 92: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

92

Frames and Arrays

For example, you could have an array called emp that contains employees' names indexed by their employee number. So emp[1] would be employee number one, emp[2] employee number two, and so on.

To create an Array object: 1. arrayObjectName = new Array([arrayLength])

2. arrayObjectName = new Array([element0, element1, ..., elementn])

arrayObjectName is either the name of a new object or a property of an existing object.

Page 93: 1 CS 21A Beginning JavaScript Programming Introduction to JavaScript Programming Sonny Huang

93

Frames and Arrays

When using Array properties and methods, arrayObjectName is either the name of an existing Array object or a property of an existing object.

First array element is 0.

In this situation the currentMonth[0]’s value is empty.