34
617 Back Close JavaScript: Formal Syntax Now that we have seen a few examples we should be able to pick up the main aspects of JavaScript. But let us formally introduce these concepts: Using JavaScript with HTML Pages Formal JavaScript Syntax Similar to many other languages at the command level

JavaScript: Formal · PDF fileJavaScript: Formal Syntax Now that we have seen a few examples we should be able to pick ... • The handler will be a JavaScript function that you’ve

  • Upload
    vanngoc

  • View
    217

  • Download
    1

Embed Size (px)

Citation preview

617

JJIIJI

Back

Close

JavaScript: Formal SyntaxNow that we have seen a few examples we should be able to pick

up the main aspects of JavaScript.

But let us formally introduce these concepts:

• Using JavaScript with HTML Pages

• Formal JavaScript Syntax

– Similar to many other languages at the command level

618

JJIIJI

Back

Close

JavaScript and the HTML Page

• You must include in an HTML page.

• Interpreter is part of the browser.

• Browser is able to debug the script and can display errors:

Safari : Check the Activity window.Internet Explorer : Upon a script error — opens a popup window

with details of the error.

619

JJIIJI

Back

Close

Writing small scripts

If use small scripts or only scripts in a web few pages then

• Include the script code in the HTML Page:

<html><head>

<title>A Sample JavaScript</title><script language=javascript>

<!--the JavaScript code goes here...

// --></script>

</head><body>...</body></html>

620

JJIIJI

Back

Close

Sharing A JavaScript Amongst Several Pages

What if you have a good script and you wish/need to use it in severaldistinct pages?:

• Bad Idea: include it every page literally

– Copy and Paste into appropriate place or Retype Code?– What if you need to change to source code?

• Good Idea:

– Store code in a separate file– Include that separate file code in the head of the page as shown

below.– Easier maintenance: Only one file edited for code changes.

621

JJIIJI

Back

Close

Including a JavaScript file

• By convention JavaScript programs are stored in files with the.js extension.

• To include the JavaScript .js file:

– Use the src attribute in the script tag:

<html><head>

<title>A Sample JavaScript File Include</title><script language=javascript src="sample.js"></script>

</head><body>

...</body></html>

622

JJIIJI

Back

Close

Variables

• Like any programming language JavaScript has variables.

• Stores data items used in the script.

• Strict rules governing how you name your variables (Much likeother languages):

– Variable names must begin with a letter, digit or underscore;– You can’t use spaces in names– Names are case sensitive so the variables fred , FRED and

frEd all refer to different variables,∗ HOWEVER It is not a good idea to name variables with

similar names– You can’t use a reserved word as a variable name, e.g. var .

623

JJIIJI

Back

Close

Creating Variables

• Use the keyword var before the variable name.

• No necessity to give the variable a value

• A value can be assigned with =.

Look at the following examples, E.g:

var num = 23;var str = "Some words";var another_str = str;var first_boolean = true;

624

JJIIJI

Back

Close

Manipulating Variables

Having defined it you can manipulate variables in a variety ofways.

These are fairly standard operations such as.

• Simple arithmetic +,-,*/ etc. E.g.

num = num + 3;

• Autoincrement ++, --

++num;

• String concatenation +:

str = str + another_str;

625

JJIIJI

Back

Close

JavaScript Data Types

JavaScript has only four types of data,

• Note: you do not declare the type in var :

Numeric :

• Integers such as 2,22 and 2,222,000 or• Floating point values like 23.42, -56.01 and 2E45.• No need to differentiate between• In fact variables can change type within program (Similar to

Perl).

626

JJIIJI

Back

Close

JavaScript Data Types (Cont.)

Strings :

• String Definition:A Collection of characters (that are not numbers).

• All of the following are strings:

"David","David Marshall""12345.432".

• Put quotes around the value to a assign a variable:

name = "David Marshall";name = ’David Marshall’;str = "34.45";

627

JJIIJI

Back

Close

JavaScript Data Types (Cont.)

Boolean :

• Variables can hold the values true and false.• Used a lot in conditional tests (later).

Null :

• Used when you don’t yet know something.• A null value means one that has not yet been decided.• It does not mean nil or zero and should NOT be used in that

way.

628

JJIIJI

Back

Close

JavaScript Variable Scoping Rules

In JavaScript variables can be either local or global:

Global :

• Variable is available to all parts of the program

Local :

• Variables are declared inside a function.• Can only be used within that function.

629

JJIIJI

Back

Close

Simple Example: Difference between Global andLocal Variables

The following (meaningless) code illustrates the difference betweenglobal and local variables:// declare the global variablesvar global_one = 32;var global_two;

function test {// this function has a local variable// a global value is copied into it// the local is then passed into a// function as a parameter

var local_var; // local variablelocal_var = global_one; // copy global

// into localfunc_two(local_var);}

function func_two(number) {// create a local variable and copy// a parameter into it

var local_var = number;}

// copying a local variable into a global// like this is not allowedglobal_two = local_var;

630

JJIIJI

Back

Close

Comments

The last global/local scoping example contained some JavaScriptcomments:

• Each line of a comment is defined by two slashes // , and

– Comments continue from that point (// )to the end of the line.– All code form // to end of line are ignored by Javascript

• For example:

// this is a JavaScript comment

// var i = 1; this variable assignment is ignored// as it is commented out

• No way of commenting large blocks of text as a block in JavaScript.

– If you want a block comment then you have to comment eachand every line – as in above example.

631

JJIIJI

Back

Close

JavaScript Control Statements

if ...else

• Easy - and useful even in the simplest of scripts.

• Similar to other languages

Here’s an example:

if(browser == "IE") {document.alert("You’re using Explorer");}else {document.alert("Nope, that’s not Explorer");}

632

JJIIJI

Back

Close

Multiple if .. else statements

You might want to test for more than one possible condition at thesame time.

In that case you must nest your if ...else statements:

if(today == "Monday") {its_monday();}else {if(today == "Tuesday") {its_tuesday();}else {another_day();}

633

JJIIJI

Back

Close

for loops

The basic syntax is:

for(counter = 0; count <= n; count++)

Use as with Java and Perl.

634

JJIIJI

Back

Close

While statement

The basic syntax is (as with Java and Perl):

while(boolean condition)

For example:

var cond = false;

while(cond == false) {// do something

if(something happens) {cond = true;

}

// more processing}

635

JJIIJI

Back

Close

What happens if you want to be able to leap out of the middleof a loop?

• Create a construct based around a while loop withif statementsembedded in it

var answer = 0;var correct = 42;var done = false;var cnt = 0;

while((done = false) && (cnt < 3)) {answer = prompt("What is the answer

to the meaning of life?", "0");if(answer = correct) {

done = true;}else {

cnt++;}

636

JJIIJI

Back

Close

}

637

JJIIJI

Back

Close

What happens if you want to be able to leap out of the middleof a loop?

Better to Use break

• Use the break statement, for example:

for(cnt = 0; cnt < 3; cnt++) {answer = prompt("What is the is

answer to the meaning of life?", "0");if(answer = correct) {

break;}

}

• Use break with care.

– Your loops should always be designed to run smoothly.– When you break , variables maybe in unknown states.

638

JJIIJI

Back

Close

Operators

JavaScript has two types of operator for :

• Tests of logic

• Affecting variable values.

We have met some before the others should obvious.

639

JJIIJI

Back

Close

Table of Operators: Logical Operators

== equal to!= not equal toOperator Description> greater than>= greater than or

equal to< less than<= less than or

equal to&& logical AND|| logical OR

640

JJIIJI

Back

Close

Table of Operators: Operators on Variables

= variable assignment+,-,/,*,% Common arithmetic+ String Concatenate+= add then assign-= subtract then assign*= multiply then assign/= divide then assign%= modulus division then assign++ autoincrement-- autodecrement! logical not

641

JJIIJI

Back

Close

Functions

We have already seen some simple JavaScript functions in action.

The syntax for defining functions is:

function name (parameters )

{// Function code goes here

}

642

JJIIJI

Back

Close

Parameter Passing

• Not every function accepts parameters.

• Not all values have to be passed as parameters — global variables?

• Using only Global variables can get messy

• Pass only values needed by function — parameters

Simple Parameter Passing Example:

function about_you(name, age, shoesize){document.write("<h1>All About You</h1>");document.write("<p><strong>Your Name is:

</strong>" + name);document.write("<p><strong>You Are</strong>"

+ age + "Years Old");document.write("<p><strong>Your Shoe Size is:

</strong>" + shoesize);}

643

JJIIJI

Back

Close

Using about you() in a General JavaScript ?

Simply call the function like this from within another function ofmore complex script:

function another_function() {......about_you(’David’, 37, 9);......

}

644

JJIIJI

Back

Close

Using about you() in a Web Page?

The function might be called like this as the page is loaded:

<html><head>

<script language="javascript">

function about_you(name, age, shoesize){document.write("<h1>All About You</h1>");document.write("<p><strong>Your Name is:

</strong>" + name);document.write("<p><strong>You Are</strong>"

+ age + "Years Old");document.write("<p><strong>Your Shoe Size is:

</strong>" + shoesize);</script>

</head><body onLoad="about_you(’David’, 37, 9)"></body></html>

645

JJIIJI

Back

Close

How are parameters passes into to functions in JavaScript?

This is not what you might first expect?

• Parameters are passed as arrays.

• Every function has two properties with information about theparameters.

function.arguments : The array of parameters that have beenpassed.

function.arguments.length : The number of parameterspassed into the function.

646

JJIIJI

Back

Close

Some Useful JavaScript Functions

JavaScripts has many inbuilt functions:

• Usual Maths functions for trigonometry, sin(), cos() etc.

• and many other standard stuff.

It also has many other useful but not so obvious functions, forexample:

parseInt() : takes in a string as parameter and returns it in integerformat.,

parseFloat() : takes a string as parameter and returns a floatingpoint representation of it

eval() : String versions of mathematical expressions can be passedinto the function where they are evaluated and the result returnedas an integer.

• Ideal for bringing simple interactivity to a page.• For instance:

eval("32 * 75674.21");

647

JJIIJI

Back

Close

Events

JavaScript is an event-driven system:

• Nothing happens in a JavaScript unless it is initiated by an eventoutside the script

– Commonly a Browser event – That is to say the Browser triggersthe event

– We have seen the onLoad and onUnLoad events already.

What is an Event?

• An event is any change that the user makes to the state of thebrowser.

648

JJIIJI

Back

Close

JavaScript Events

Event Descriptionblur Input focus is moved from the object.

Usually when moving from a field of a formor from the form itself.

change Value of a field in a form has beenchanged by the user enteringor deleting data.

click Mouse is clicked over anelement of a page.

focus Input focus is given to an element.The reverse of blur.

load Page is loaded by the browser.mouseover Mouse pointer is moved over an element.select A field on a form is selected by clicking

the mouse or tabbing from the keyboard.submit When a form is submitted

(the submit button is clicked).unload User leaves the Web page.

649

JJIIJI

Back

Close

JavaScript Event Handlers

The processing associated with an event is managed by an eventhandler.

The list of event handlers is:

• onBlur

• onChange

• onClick

• onFocus

• onLoad

• onMouseover

• onSelect

• onSubmit

• onUnload

650

JJIIJI

Back

Close

Associating JavaScript Event Handlers with HTML Elements

As we have already seen:

• JavaScript Event Handlers are associated with an HTML elementas part of its definition in the HTML source code:

<element attributes event ="handler ">

• The handler will be a JavaScript function that you’ve definedelsewhere and which is available to the element.

For Example:

<body onLoad="init()">