53
1 Browser Scripting Browser Scripting JavaScript

1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

  • View
    231

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

1

Browser ScriptingBrowser Scripting

JavaScript

Page 2: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

2

Dynamic HTMLDynamic HTML

XHTMLXHTML

content

CSSCSS

style rules

appearance

ScriptingScriptingLanguageLanguage

manipulatemanipulate

Page 3: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

3

IntroductionIntroduction

Page 4: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

4

Client-Server ArchitectureClient-Server Architecture

• In a client-server architecture, computations are done either in the client or in the server (or both)

• In some cases, we can choose whether to perform the computation in the client or the server side- For example, validating forms

• There are cases where we cannot choose where to perform the computation- For example, accessing a database

Page 5: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

5

Client Side TechnologiesClient Side Technologies

• JavaScript- Developed by Netscape, standardized by ECMA

- Supported by all browsers (although not all support the standard)

• VBScript- Developed by Microsoft

- Supported only by Microsoft Internet Explorer

- A light version of Microsoft Visual Basic

• Java Applets - Developed by Sun

• Flash- Developed by Macromedia (acquired by Adobe in 2005)

Page 6: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

6

About AppletsAbout Applets

• An applet is a Java class that runs in a frame that is embedded in a Web page

<object type="application/x-java-applet" classid="myApplet.class" width="x" height="y">

• When a browser loads the Web page, the applet byte-code (.class file) is downloaded to the client box and executed by the browser

• Commonly used for games, graphics, etc.

Page 7: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

7

Page 8: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

8

Browser ScriptingBrowser Scripting

• Browser scripts are procedural programs embedded inside HTML

<script type="text/javascript">script</script>

<script type="text/vbscript">script</script>

• Can read and manipulate HTML elements, CSS properties, and the browser itself

Page 9: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

Web browser

HTML Page:

<script>

…code..…

</script>

InternetHTML/HTTP

TCP/IP

HTML/HTTP

TCP/IP

Web

(HTTP)

Server

HTML

pages with

embedded

script

built-in

Script

interpreter

Web Architecture for ScriptsWeb Architecture for Scripts

Client Server

Page 10: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

10

Why are Scripts Needed?Why are Scripts Needed?

• Generating HTML content dynamically

• Monitoring and responding to user events

• Validating forms before submission

• Manipulating HTTP cookies

• Interaction among the frames and windows of the browser

• Interacting with the server (w/o browser refresh)

Page 11: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

11

JavaScript HistoryJavaScript History

• Introduced in Netscape 2 (1996)

• Standardized by ECMA under the name ECMAScript (1997-1999)

• The latest version is ECMAScript 4, and it is equivalent to JavaScript 2.0

Page 12: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

12

JavaScript BasicsJavaScript Basics

Page 13: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

13

JavaScript is NOT Java!JavaScript is NOT Java!

• JavaScript is not compiled

• JavaScript is typically executed by Web browsers and not as stand-alone applications

• JavaScript and Java have some similarity in syntax

• The choice of the name is mainly for historical reasons

Page 14: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

14

Dynamic HTML Content: Dynamic HTML Content: Example 1Example 1

<html>

<head><title>JS Example</title></head> <body>

<h2>Before the script</h2>

<script type="text/javascript">

document.write('<h1>In the script<\/h1>')

</script>

<h2>After the script</h2>

</body></html>

Page 15: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

15

Page 16: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

16

Dynamic HTML Content: Dynamic HTML Content: Example 2Example 2

<html>

<head><title>JS Example</title></head><body>

<h2>Before the script</h2><h1>

<script type="text/javascript">

document.write(new Date().toLocaleString())

</script>

</h1><h2>After the script</h2>

</body></html>

Page 17: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

17

Dynamic HTML Content: Dynamic HTML Content: Example 3Example 3

<h2>Hello and

<i><script type="text/javascript">

var hours = new Date().getHours();

if (hours < 10) { document.write("good morning") }

else {document.write("good day") }

</script></i>.

</h2>

Page 18: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

18

Basic ConstructsBasic Constructs

• Statement blocks

- Semicolon (;) is optional at end of line

var x=5document.write(x);

var x=5, y=7;document.write(x+y);

if (condition) {statements if true}else {statements if false}

• Conditions: if, if-else, ?:, switch

x= (y>0)? y:0

• Loops: for, while, do-while

while (condition) {statements}

Page 19: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

19

VariablesVariables

• Variables are not typed! (but values are)- var x = 5; x="abcd";...

• Thus, the value of a variable is characterized by both value and type

• Variables are declared with var keyword:- var x; var y=5;- Without var, a variable is considered global

• A variable name consists of letters, digits, and underscores (_), - Does not begin with a digit

Page 20: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

20

Data TypesData Types

• Values have one of the following types:- number: 5, 2.3, 0xFF, 6.67e-11

- object: new Date()• Arrays: [1,"ab ba",17.234]

• null

- string: "Hello World"

- boolean: true, false

- function (discussed later)

- undefined: no value assigned...You can use typeof(x)

to get the type of x:number, string, object...

Page 21: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

21

Some of the Reserved WordsSome of the Reserved Words

abstractas

breakcasecatchclassconst

continuedefault delete

doin

instanceofinterface

isnamespace

newnull

packageprivate

publicreturnelse

export extends

falsefinal

finallyfor

function

ifimplements

import staticsuperswitch

thisthrowtruetry

typeofusevar

void whilewith

Page 22: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

22

OperatorsOperators

• Arithmetic: +   ++   -    --   *   /   %

• Comparison: == != === !== > >= < <=

• Logical: & && | || !

• Bitwise: & | ^ ~ << >> >>>

• String: +

• Assignments: = += -= *= /= <<= |= ...

Page 23: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

23

Types of EqualityTypes of Equality

• The equals == (!=) checks if both operands are equal after performing type conversion

• The equals === (!==) checks if both operands are of the same type and equal

• Example:- Is 34 == "34" ? Is 34 == "3"+"4" ? - Is 34 === "3"+"4" ? Is 34 !== "3"+"4" ?

Page 24: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

24

An ExampleAn Example

<script type="text/javascript">

for (var counter = 1 ; counter <= 8 ; ++counter) {

var fontsize = counter + 10; fontsize+="pt";

document.write("<p style='font-size: "+fontsize+"'>" + "Font size " + fontsize + " <\/p>"); }

</script>

Page 25: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

25

Page 26: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

26

FunctionsFunctions

Page 27: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

27

FunctionsFunctions

• JavaScript functions are special constructs with the operator ()

• Syntax: function fname(args...) {statements}

• Usually, functions are defined at the head - Guarantees that functions are declared before used

• Some functions are predefined- For example, parseInt(string)

• Functions can return values

Page 28: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

28

Function ExampleFunction Example

<html> <head> <script type="text/javascript"> function add(x,y) { return x+y; } </script> </head>

<body> <h1> <script type="text/javascript"> sum = add(4,5); document.write("4+5="+sum); </script> </h1> </body></html>

Page 29: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

29

Function ValuesFunction Values

• Parameters are passed to (and return from) functions by value- Assignment does not change the original parameter

• Objects are not copied but rather act as pointers- That is, properties of an object can be changed when

given as an argument of a function

Page 30: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

30

Undeclared ArgumentsUndeclared Arguments

• Function may receive arguments without declaring them

• Within a function, its arguments are held in the arguments array- The ith argument is arguments[i]- The number of arguments is

arguments.length

• Hence, it is possible to define functions that take any number of arguments

Page 31: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

31

An ExampleAn Example

What is the result of the following code?

function myConcat(separator) { var result="";   // iterate through arguments    for (var i=1; i<arguments.length; i++) {       result += arguments[i] + separator;    }    return result;}

con = myConcat(", ","red","orange","blue");

Page 32: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

32

Predefined FunctionsPredefined Functions

• JavaScript includes several predefined functions

• For example,- eval(code-string) – gets a string of JavaScript

code, evaluates it and executes it• It allows dynamic code execution

- parseInt(string) – converts the beginning of string to an integer (or return NaN)

Page 33: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

33

Variable ScopesVariable Scopes

• JavaScript variables are recognized inside their declaration scope

• Hence, global variables should be declared outside the functions

• A variable declared in a function can also be global, if var is omitted

Page 34: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

34

Objects and ArraysObjects and Arrays

Page 35: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

35

Object ModelObject Model

• JavaScript objects are similar to associative arrays

• That is, an object associates identifiers (e.g., firstName) with values (attributes) (e.g., "John")

• Those values may be other objects (nested objects)

• Those values can also be functions (methods)- e.g., function setPersonAge(age) {this.age = age}

• When o.f() is invoked, o can be referred to as this

Page 36: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

36

Creating ObjectsCreating Objects

• Objects can be created in several ways:

• Object initializers

• Object assignments

var theNissan = {make:"Nissan", year:2003, color:"blue"}

theMazda = { make:"Nissan" } theMazda.year = 2002;theMazda.color="black";

Page 37: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

37

Creating Objects (cont)Creating Objects (cont)

• Object Constructors- Define a constructor function- Create the new object using new

function car(make,year,color) { this.make = make this.year = year this.color = color}

theHonda = new car("Honda", 2001, "green")

Page 38: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

38

Defining MethodsDefining Methods

• Methods are associated with objects just like attributes

function niceString() { return "<span style='color:"+ this.color + "'>" + this.make + " "+ this.year + "<\/span>"}

theNissan = {make:"Nissan",year:2003,color:"blue",str:niceString}

Page 39: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

39

Defining Methods (cont)Defining Methods (cont)

function car(make,year,color) { this.make = make this.year = year this.color = color this.str = niceString}

theHonda = new car("Honda", 2001, "green")

theNissan = {make:"Nissan", year:2003, color:"blue"} theNissan.str = niceString;

Page 40: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

40

Accessing Object PropertiesAccessing Object Properties

• Object attributes can be accessed in several ways:- object.attName- object["attName"]

• Thus, object methods are invoked in Java/C++ style:- object.method(arguments)

• Alternatively:- object["method"](arguments)

Page 41: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

41

The Complete ExampleThe Complete Example

function niceString() { return "<span style='color:"+ this.color + "'>" + this.make + " "+ this.year + "<\/span>"}

function car(make,year,color) { this.make = make; this.year = year; this.color = color; this.str = niceString}

var theHonda = new car("Honda", 2001, "green");

document.write(theHonda.str());

Page 42: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

42

Array ObjectsArray Objects

• Arrays are supported as objects

• Attribute length

• Methods include:concat, join, pop, push, reverse, sort, shift, ...

• Arrays can be passed to functions as arguments

Page 43: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

43

Creating ArraysCreating Arrays

• var a = ["red", "blue", "green"]

- Allocates an array of 3 cells and initializes the

values

• var b = new Array(5)

- Allocates an array of 5 cells without initializing

• var c = new Array()

- Creates a new empty array

Page 44: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

44

Array ElementsArray Elements

• Array elements need not have the same type- arr1 = ["hello", 1, true]

• Java-like access: arr[i]

• Out-of-bounds assignments automatically enlarge the array - arr1[10] = 66

• Multi-dimensional arrays are arrays of arrays- var matrix = [ [0, 1, 1], [1, 1, 0], [0, 0, 0]]

Page 45: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

45

MiscellaneousMiscellaneous

Page 46: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

46

JavaScript and XHTMLJavaScript and XHTML

• Embedding JavaScript code inside XHTML may violate XML rules - e.g., x<5 && x>2

• One solution is to import JavaScript code from external files, e.g.: <script type="..." src="jsfile.js"/>- Always a good habit...

• Another solution: wrap the code in an XML CDATA section

Page 47: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

47

Wrapping Code in Wrapping Code in CDATACDATA

<script type="text/javascript"/>

//<![CDATA[

regular JavaScript code

...

//]]>

</script>

Page 48: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

48

The String ObjectThe String Object

• JavaScript has a built-in String object- not the primitive string!

• Create a String object from a string primitive:- myString = new String("This is a string object")

• Extract the primitive string from a String object:- str = myString.valueOf()

Page 49: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

49

StringString Common Methods Common Methods

• charAt (index)

• charCodeAt(index)

• concat(string)

• fromCharCode(value1, value2, …)

• indexOf(substring, index)

• lastIndexOf(substring, index)

• slice(start, end)

• split(string)

• substr(start, length)

• substring(start, end)

• toLowerCase()

• toUpperCase()

• valueOf()

• match(regexp)

Page 50: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

50

An Example - Format An Example - Format VerificationVerification

• What does the following function do?

function getString() { var result = null; while(result==null) { var answer = prompt("Your first name:") if(answer!=null) { result = new String(answer); result = result.toLowerCase().match("^[a-z]+$"); } if(result==null) { alert("Don't mess with me!") } } return answer }

Page 51: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

51

The The MathMath Object Object

• The object Math is used for mathematical operations- E.g., Math.pow(x,2)

• Other useful functions:

• abs(x)

• round(x)

• ceil(x)

• floor(x)

• cos(x)

• sin(x)

• tan(x)

• exp(x)

• pow(x, y)

• sqrt(x)

• log(x)

• max(x, y)

• min(x, y)

• Math Also includes constants such as: Math.E, Math.PI

Page 52: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

52

The The withwith Statement Statement

• Establishes the default object for a set of statements

• Within the set of statements, any property references that do not specify an object are assumed to be of the default object

var a, x, yvar r=10with (Math) { a = PI * r * r; x = r * cos(PI); y = r * sin(PI/2) }

Page 53: 1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

53

The Date ObjectThe Date Object

• Create the current date: new Date()

• Create an arbitrary date: new Date(date-string)

• Common methods of Date:

• getDate()

• getFullYear()

• getMonth()

• getDay

• getTime()

• getHours()

• getMinutes()

• getSeconds()

• getMilliseconds()

• toLocaleString()