javascript, fifth edition chapter 1 introduction to javascript

39
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript

Upload: lilian-simmons

Post on 26-Dec-2015

238 views

Category:

Documents


1 download

TRANSCRIPT

JavaScript, Fifth Edition

Chapter 1Introduction to JavaScript

Development of JavaScript

JavaScript is a subset of Java Differences between Java and JavaScript:

Development of JavaScript

Jscript is a version of JavaScript supported by Internet Explorer

The European Computer Manufacturers Association (ECMA) develops scripting standards◦ The standard is called ECMAScript but browsers

still generally call is JavaScript

Running script Two places where script executes:

◦ Server-side - programs that run on the server that hosts a Web site◦ Client-side - programs that run on each user’s computer

Adding JavaScript to Your Web Pages

JavaScript, Fifth Edition 5

JavaScript, Fifth Edition 6

Using the <script> Element

• Scripts– JavaScript programs contained within a Web page– A JavaScript program can either be placed directly in

a Web page file or saved in an external text file

• <script> element– Tells the browser that the scripting engine must

interpret the commands it contains– <script type="mime-type">

• Tells the browser which scripting language and which version of the scripting language being used

JavaScript, Fifth Edition 7

Using the <script> Element

<script type="mime-type">

script statements;

</script>– Each statement inside the script tags is a single line

that indicates an action for the browser to take– The semicolon notifies the browser that it has reached

the end of the statement

Understanding JavaScript Objects

• Object– any item—from the browser window itself to a document displayed in

the browser to an element displayed within the document

– Programming code and data

• Treated as an individual unit or component

• Procedures– Individual statements used in a computer program grouped into logical

units

– Used to perform specific tasks

• Methods– a process by which JavaScript manipulates or acts upon the properties

of an object

– Procedures associated with an object

JavaScript, Fifth Edition 8

Understanding JavaScript Objects (cont’d.)

• Property– Piece of data associated with an object– Assign value to a property using an equal sign

• Argument– Information that must be provided to a method

• Passing arguments– Providing an argument for a method

JavaScript, Fifth Edition 9

JavaScript, Fifth Edition 10

Using the write() and writeln()Methods

• Document object– Represents content of a browser’s window

• To write text to a Web page, use the following JavaScript commands:

document.write(“text”);

or

document.writeln(“text”)’

where text is the content to be written to the page.

JavaScript, Fifth Edition 11

Using the write() and writeln()Methods

document.write(“text”);

or

document.writeln(“text”)’

The document.write() and document.writeln() methods are identical, except that the document.writeln() method preserves any line breaks in the text string

– Both methods require a text string as an argument– Text string (aka literal string)

• Text contained within double or single quotation marks

JavaScript, Fifth Edition 12

Figure 1-6 Output of a script that uses the writeln() method of the Document object

Using the write() and writeln()Methods (cont’d.)

Case Sensitivity in JavaScript

• JavaScript is case sensitive

• Ignores most occurrences of extra white space

• Do not break a statement into several lines

• Within JavaScript code:– Object names must always be all lowercase

JavaScript, Fifth Edition 13

Let’s Practice

• Write a basic HTML page containing script tags.

• Inside the script, use the document object to write out your name

Syntax is: objectname.methodname

document.write

JavaScript, Fifth Edition 14

Adding Comments to a JavaScript Program

• Comments– Nonprinting lines placed in code containing various

types of remarks

• Line comment– Hides a single line of code– Add two slashes // before the comment text

• Block comments– Hide multiple lines of code– Add /* before the first character included in the block

and */ after the last character in the block

JavaScript, Fifth Edition 15

Variables

JavaScript, Fifth Edition 16

Using Variables

• Variables– A variable is a named item in a program that stores

information– Values a program stores in computer memory

• Assigning a value to a variable– Same as storing a value in a variable

JavaScript, Fifth Edition 17

Declaring a variable• You can declare variables with any of the following JavaScript

commands:

var variable;var variable = value;variable = value;

where variable is the name of the variable and value is the initial value of the variable. • Use reserved keyword var to create variables

• The first command creates the variable without assigning it a value; • the second and third commands both create the variable and assign

it a value

• Assignment operator: equal sign (=)– Assigns value on the right side of the expression to the variable on the

left side of the expressionJavaScript, Fifth Edition 18

Assigning Variable Names

• Identifier– Name assigned to a variable– Rules and conventions

• Must begin with an uppercase or lowercase ASCII letter, dollar sign ($), or underscore ( _ )

• Can use numbers in an identifier: not as the first character

• Cannot include spaces in an identifier

• Cannot use reserved words for identifiers

• Reserved words (keywords)– Special words: part of the JavaScript language syntax

JavaScript, Fifth Edition 19

JavaScript, Fifth Edition 20

Table 1-2 JavaScript reserved words

Assigning Variable Names (cont’d.)

JavaScript variable types

• Numeric variables– any number, such as 13, 22.5, etc

• String variables– any group of text characters, such as “Hello” or “Happy

Holidays!”– Must be enclosed within either double or single quotations (but

not both)

• Boolean variables– accepts only true and false values

• Null variables– has no value at all

• You must declare a variable before using itJavaScript, Fifth Edition 21

JavaScript, Fifth Edition 22

Printing variables

• Printing a variable– Pass variable name to document.write() or document.writeln()method

– Do not enclose it in quotation marks

Figure 1-8 Results of script that assigns the value of one variable to another

The + sign

• JavaScript is a weakly typed language

• The + symbol can be used with either numeric values or text strings

var total = 5 + 4;

var emLink = "cadler" + "@" + "mpl.gov";

JavaScript, Fifth Edition 23

JavaScript, Fifth Edition 24

The + sign

– The plus sign can be used to perform arithmetic operations involving variables containing numeric values

Figure 1-9 Results of script that adds the values of two variables

Modifying variables

• Modifying variables– Change a variable’s value at any point in a script

• Use a statement including the variable’s name

• Followed by an equal sign

• Followed by the value to assign to the variable

var total = 5 + 4;var total = 22;

JavaScript, Fifth Edition 25

Building Expressionsvar total = 5 + subtotal;

• Variables and data are useful when used in an expression

• Expression– Literal value or variable or a combination of literal

values, variables, operators, and other expressions• Can be evaluated by JavaScript interpreter to produce

a result

JavaScript, Fifth Edition 26

Building Expressionsvar total = 5 + 4;

• Use operands and operators to create expressions– Operands

• Variables and literals contained in an expression

• Literal– Value such as a literal string or a number

– Operators• Symbols used in expressions to manipulate operands

+, -, *, /

JavaScript, Fifth Edition 27

Lets Practice

• Write a basic HTML page containing script tags.

• Inside the script, create a variable to store your name in.

• Use the document object to write out the variable’s contents

Syntax is: objectname.methodname, as in

document.write()

JavaScript, Fifth Edition 28

JavaScript, Fifth Edition 29

Understanding Events

• Event– Specific circumstance monitored by JavaScript– Script can respond to in some way– Allows users to interact with Web pages

• Common events: actions users perform

• Can also monitor events not resulting from user actions

JavaScript, Fifth Edition 30

Table 1-3 JavaScript events

Understanding Events (cont’d.)

JavaScript, Fifth Edition 31

Understanding Events (cont’d.)

• Working with elements and events– Events: associated with HTML elements– Event handler

• Code that executes in response to a specific event

– JavaScript code for an event handler• Can be contained within the quotation marks following

the name of the JavaScript event handler

<element eventhandler=“Javascript Code”><input type=“button” onclick=“window.alert(‘hi there’);” />

JavaScript, Fifth Edition 32

Table 1-4 XHTML elements and their associated events

Understanding Events (cont’d.)

JavaScript, Fifth Edition 33

Referencing web page elements

– Append element’s name to the name of any elements in which it is nested

• Start with the Document object

– Specific element properties• Appended to the element name

– Allows for the retrieval of information about an element or the ability to change the values assigned to its attributes

Structuring JavaScript Code

JavaScript, Fifth Edition 34

JavaScript, Fifth Edition 35

Including a <script> Element for Each Code Section

• Can include as many script sections as desired– Must include a <script> element for each section– Example code below

• See Figure 1-13 for results

JavaScript, Fifth Edition 36

Placing JavaScript in the Document Head or Document Body

• <script> element placement varies– Can place in the document head or document body– Statements in a script

• Rendered in the order in which they appear in the document

– General rule• Place as much JavaScript code as possible in the

document head

• Important if code performs behind-the-scenes tasks required by script sections located in the document body

JavaScript, Fifth Edition 37

Creating a JavaScript Source File

• External file containing JavaScript code– Usually designated by the .js file extension

• Can legally have any extension

– Contains only JavaScript statements• No <script> element and no XHTML elements

– Use the src attribute of the <script> element

• Advantages– Neater code; code sharing; ability to hide JavaScript

code from incompatible browsers

• Can use embedded JavaScript code and JavaScript source files combination

JavaScript, Fifth Edition 38

Validating Web Pages

• Validating parser– Checks for a well formed Web page– Verifies document conforms to a specific DTD

• Validation– Process of verifying a well-formed document and

checking the elements in your document

• Web development tools offer validation capabilities

• Validating services found online– W3C Markup Validation Service:

• http://validator.w3.org

JavaScript, Fifth Edition 39

Writing Valid JavaScript Code

• JavaScript statements contain symbols– Prevents HTML document from being well formed– Web pages will not validate when they contain script

• Two options to resolve validation issue– Move code into a source file– Keep JavaScript code within the document

• Enclose code within a <script> element within a CDATA