Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client...

74
Javascript Javascript Browser – Client Side Processing Browser – Client Side Processing Activity page/examples: Activity page/examples: http://comp.fsksm.utm.my/ http://comp.fsksm.utm.my/ ~rosely/js/ ~rosely/js/

Transcript of Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client...

Page 1: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JavascriptJavascript

Browser – Client Side ProcessingBrowser – Client Side Processing

Activity page/examples:Activity page/examples:

http://comp.fsksm.utm.my/~rosely/js/http://comp.fsksm.utm.my/~rosely/js/

Browser – Client Side ProcessingBrowser – Client Side Processing

Activity page/examples:Activity page/examples:

http://comp.fsksm.utm.my/~rosely/js/http://comp.fsksm.utm.my/~rosely/js/

Page 2: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

OutlineOutline

• Introduction

•Fundamental of JavaScript

• Javascript events management

•DOM and Dynamic HTML (DHTML)

Page 3: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Introduction - OutlineIntroduction - Outline

• Introduction– What is Javacript?– What Javascript can do?– Examples usage of Javascript– How to use Javascript?

Page 4: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

What is JavascriptWhat is Javascript

• Official name: ECMAScript maintain Official name: ECMAScript maintain by ECMA organisationsby ECMA organisations

• ECMA 262 – official Javascript ECMA 262 – official Javascript standard based on Javascript standard based on Javascript (Netscape) & Jscript (Microsoft)(Netscape) & Jscript (Microsoft)

• Invented by Brendan Eich at Invented by Brendan Eich at Netscape (with Navigator 2.0) Netscape (with Navigator 2.0)

• Development is still in progress!Development is still in progress!

Page 5: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

What is JavascriptWhat is Javascript

• Java and Javascript is not the SAME – Java and Javascript is not the SAME – only similar to Java and C++only similar to Java and C++

• The fundamentals of Javascript are The fundamentals of Javascript are similar to Java and/or C++ similar to Java and/or C++

Page 6: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

What is Javascript?What is Javascript?

• was designed to add interactivity to HTML was designed to add interactivity to HTML pagespages

• Is a scripting languageIs a scripting language• an interpreted language (means that scripts an interpreted language (means that scripts

execute without preliminary compilation) execute without preliminary compilation) • Case-sensitiveCase-sensitive• Must be embedded into HTMLMust be embedded into HTML• Browser dependentBrowser dependent• Execute whenever the HTML doc. which Execute whenever the HTML doc. which

contain the script open by browser.contain the script open by browser.• Everyone can use JavaScript without Everyone can use JavaScript without

purchasing a license purchasing a license

Page 7: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

What Javascript can do?What Javascript can do?

• JavaScript gives HTML designers a JavaScript gives HTML designers a programming tool programming tool

• JavaScript can put dynamic text into an JavaScript can put dynamic text into an HTML page HTML page

• JavaScript can react to events JavaScript can react to events • JavaScript can read and write HTML JavaScript can read and write HTML

elements elements • JavaScript can be used to validate data JavaScript can be used to validate data • JavaScript can be used to detect the JavaScript can be used to detect the

visitor's browser visitor's browser • JavaScript can be used to create cookiesJavaScript can be used to create cookies

Page 8: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Examples usage of Javascript -Examples usage of Javascript -activity 01activity 01Examples usage of Javascript -Examples usage of Javascript -activity 01activity 01

• Limited capability applicationLimited capability application– ClocksClocks– Mouse Trailers (an animation that follows Mouse Trailers (an animation that follows

your mouse when you surf a site)your mouse when you surf a site)– Countdown timerCountdown timer– Drop Down MenusDrop Down Menus

• The objective of Javascript is not The objective of Javascript is not for creating full-blown application for creating full-blown application running in a browser!running in a browser!

• Limited capability applicationLimited capability application– ClocksClocks– Mouse Trailers (an animation that follows Mouse Trailers (an animation that follows

your mouse when you surf a site)your mouse when you surf a site)– Countdown timerCountdown timer– Drop Down MenusDrop Down Menus

• The objective of Javascript is not The objective of Javascript is not for creating full-blown application for creating full-blown application running in a browser!running in a browser!

Page 9: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Examples usage of JavascriptExamples usage of Javascript

• Event managementEvent management• Form management & verificationForm management & verification• Dynamic HTML (DHTML)Dynamic HTML (DHTML)• Client-Server application - AJAXClient-Server application - AJAX

Page 10: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

How to use Javascript?– activity 02 How to use Javascript?– activity 02

• Inside the head tag (head section)Inside the head tag (head section)

• Within the body tag (body section)Within the body tag (body section)

• In an external file (external script)In an external file (external script)

Page 11: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

How to use Javascript?- head section

<html><head><script type="text/javascript">function message(){ alert("This alert box was called with the onload event");}</script></head>

<body onload="message()">

</body></html>

Page 12: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

How to use Javascript?- body section

<html><head></head>

<body>

<script type="text/javascript">document.write("This message is written by JavaScript");</script>

</body></html>

Page 13: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

How to use Javascript?- external script<html><head><script src="myjs.js"></script></head><body><input type="button" onclick="popup()" value="Click Me!"></body></html>

// JavaScript Document (myjs.js)function popup() {alert("Hello World")}

Page 14: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

How to use Javascript?

• All code inside head tag (except in All code inside head tag (except in function) will be executed first before function) will be executed first before the html <body> loadthe html <body> load

• Put global variables in the <head> Put global variables in the <head> section scriptsection script

• Use document.write/ln to send html Use document.write/ln to send html output output

• Use window.prompt to get user inputUse window.prompt to get user input

Page 15: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Use in alert boxUse in alert box

Page 16: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Debugging Errors:Activities 03

Debugging Errors:Activities 03

Click this. Warning icon means there are some errors in your script

Page 17: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Debugging Errors:Debugging Errors:

Page 18: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Simple JS application – Simple JS application – input/outputinput/output

Page 19: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript FundamentalJavascript Fundamental

• A light Java/C++A light Java/C++• All other things are more or less the All other things are more or less the

same:same:– Keyword, variablesKeyword, variables– OperatorOperator– Conditional statementConditional statement– Looping etc.Looping etc.

• Case sensitiveCase sensitive• No strong typing in JS for variableNo strong typing in JS for variable

Page 20: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript VariablesJavascript Variables

• Variables name – case sensitiveVariables name – case sensitive• No typing!No typing!• Can change type during executionCan change type during execution

– Activity 05 - aActivity 05 - a

• Use double qoute for character and Use double qoute for character and string variablestring variable

• Cannot use reserve word for variable Cannot use reserve word for variable name!name!

• Variables name – case sensitiveVariables name – case sensitive• No typing!No typing!• Can change type during executionCan change type during execution

– Activity 05 - aActivity 05 - a

• Use double qoute for character and Use double qoute for character and string variablestring variable

• Cannot use reserve word for variable Cannot use reserve word for variable name!name!

Page 21: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

OUTPUT:

10rosely25

OUTPUT:

10rosely25

Page 22: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS – Reserve WordJS – Reserve Word

Page 23: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript variables Javascript variables operationoperation• Arithmetic operations – same as Java/C++Arithmetic operations – same as Java/C++• + operators is overloaded, can be used for string+ operators is overloaded, can be used for string• Number + string (or vice versa), result string Number + string (or vice versa), result string

– Activity 05 - bActivity 05 - b

– A = 2 + 5 (result 7)A = 2 + 5 (result 7)– A = 2 + “5” (result 25)A = 2 + “5” (result 25)– A = A + 2 (result 252)A = A + 2 (result 252)

Page 24: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

OUTPUT:

225252

OUTPUT:

225252

Page 25: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS OperatorsJS Operators

Page 26: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS OperatorsJS Operators

Page 27: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript – Conditional Javascript – Conditional expressions – expressions – activity 06activity 06Javascript – Conditional Javascript – Conditional expressions – expressions – activity 06activity 06

• If else, switch statement – same as If else, switch statement – same as C++/JavaC++/Java

• BooleanBoolean– Value 0, false = falseValue 0, false = false– Value 1, true = true Value 1, true = true

• String comparison, use the quote!String comparison, use the quote!– if (password == “007”)if (password == “007”)

• Check the example!Check the example!

• If else, switch statement – same as If else, switch statement – same as C++/JavaC++/Java

• BooleanBoolean– Value 0, false = falseValue 0, false = false– Value 1, true = true Value 1, true = true

• String comparison, use the quote!String comparison, use the quote!– if (password == “007”)if (password == “007”)

• Check the example!Check the example!

Page 28: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript – Conditional Javascript – Conditional expressionsexpressions• Special conditional operatorSpecial conditional operator

– variablename=(condition)?value1:value2  variablename=(condition)?value1:value2  – If true value1 assigned else value2 assigned to If true value1 assigned else value2 assigned to

variablenamevariablename

greeting = (visitor == "PRES") ? "Dear President “ : "Dear "; greeting = (visitor == "PRES") ? "Dear President “ : "Dear ";

Page 29: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript – LoopJavascript – Loop

• for loop, while loop – same as C++/Javafor loop, while loop – same as C++/Java• Use Use breakbreak statement to exit loop statement to exit loop• JavaScript JavaScript For...InFor...In Statement Statement

– used to loop (iterate) through the used to loop (iterate) through the elements of an array or through the elements of an array or through the properties of an object.properties of an object.

– var mycars = new Array(); var mycars = new Array(); – for (x in mycars) for (x in mycars)

• document.write(mycars[x] + "<br />");document.write(mycars[x] + "<br />"); •Activity 07Activity 07

• for loop, while loop – same as C++/Javafor loop, while loop – same as C++/Java• Use Use breakbreak statement to exit loop statement to exit loop• JavaScript JavaScript For...InFor...In Statement Statement

– used to loop (iterate) through the used to loop (iterate) through the elements of an array or through the elements of an array or through the properties of an object.properties of an object.

– var mycars = new Array(); var mycars = new Array(); – for (x in mycars) for (x in mycars)

• document.write(mycars[x] + "<br />");document.write(mycars[x] + "<br />"); •Activity 07Activity 07

Page 30: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript ArrayJavascript Array– – activity 08 (.1, .2, .3)activity 08 (.1, .2, .3)Javascript ArrayJavascript Array– – activity 08 (.1, .2, .3)activity 08 (.1, .2, .3)

• Array is a built-in object in JSArray is a built-in object in JS– http://www.w3schools.com/jsref/jsref_obj_arrayhttp://www.w3schools.com/jsref/jsref_obj_array

.asp.asp

• Means have methods and propertiesMeans have methods and properties• Important properties: Important properties:

– length (total elements) length (total elements) – For traversing array elementsFor traversing array elements

• Example method: Example method: – sort() : sorting array elementssort() : sorting array elements– join() : combine all array elements into a stringjoin() : combine all array elements into a string

Page 31: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript Array - creatingJavascript Array - creating

var a = new Array(12);var a = new Array(12);

var b = new Array();var b = new Array();

var c = new Array(12,10,11);var c = new Array(12,10,11);

var d = [12,10,11]; // same as cvar d = [12,10,11]; // same as c

var e = [1,,,10]; // 4 elements array, only first & last var e = [1,,,10]; // 4 elements array, only first & last element initializedelement initialized

Page 32: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript array: inserting Javascript array: inserting valuesvalues

var A =new Array();var A =new Array();

A[0]= 10;A[0]= 10;

A[1]= 20;A[1]= 20;

A[2]=“Ali”;A[2]=“Ali”;

A[3]=2.34;A[3]=2.34;

Result:Result:A[0] 10

A[1] 20

A[2] Ali

A[3]2.34

Page 33: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS Array: creating and JS Array: creating and accessingaccessing

Page 34: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS Array: sort methodJS Array: sort method

Page 35: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript Array - Javascript Array - MultidimensionalMultidimensional– – activity 08.4activity 08.4

Javascript Array - Javascript Array - MultidimensionalMultidimensional– – activity 08.4activity 08.4• Technically, JavaScript doesn't support Technically, JavaScript doesn't support

multi-dimensional arraysmulti-dimensional arrays

• Because array is an object, you can put Because array is an object, you can put object inside of another object, so object inside of another object, so emulating a multi dimensional arrayemulating a multi dimensional array

• So it is possible to have a different So it is possible to have a different dimension (column) for each row!dimension (column) for each row!

Page 36: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript Array - Javascript Array - MultidimensionalMultidimensionalJavascript Array - Javascript Array - MultidimensionalMultidimensional

• var myarray=new Array(3)var myarray=new Array(3)

• Create a multidimensional arrayCreate a multidimensional array

Page 37: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript Array - Javascript Array - MultidimensionalMultidimensionalJavascript Array - Javascript Array - MultidimensionalMultidimensional

Page 38: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript Array - Javascript Array - MultidimensionalMultidimensionalJavascript Array - Javascript Array - MultidimensionalMultidimensional

Page 39: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript Array - Javascript Array - MultidimensionalMultidimensionalJavascript Array - Javascript Array - MultidimensionalMultidimensional

Page 40: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript Array - Javascript Array - MultidimensionalMultidimensionalJavascript Array - Javascript Array - MultidimensionalMultidimensional

Page 41: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS Array: AssociativeJS Array: Associative- - Activity 08.5Activity 08.5JS Array: AssociativeJS Array: Associative- - Activity 08.5Activity 08.5

• Using a similar access technique to hash functionUsing a similar access technique to hash function

• In this case, the index of an array is using a word In this case, the index of an array is using a word or key instead of number.or key instead of number.

• This is where For In is use instead of For LoopThis is where For In is use instead of For Loop

Page 42: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS Array: AssociativeJS Array: Associative

Page 43: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS Array: AssociativeJS Array: Associative

• Direct access to individual elementsDirect access to individual elements

• Printing the keys!Printing the keys!

Page 44: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS Array: AssociativeJS Array: Associative

• Direct access to individual elementsDirect access to individual elements– Ichigo kurosakiIchigo kurosaki– rob luccirob lucci

• Printing the keys!Printing the keys!– BLEACHBLEACH– NARUTONARUTO– ONE_PIECEONE_PIECE

• Direct access to individual elementsDirect access to individual elements– Ichigo kurosakiIchigo kurosaki– rob luccirob lucci

• Printing the keys!Printing the keys!– BLEACHBLEACH– NARUTONARUTO– ONE_PIECEONE_PIECE

Page 45: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS Array: AssociativeJS Array: Associative

• Printing all elements in array using For..In Printing all elements in array using For..In and For..Loopand For..Loop

Page 46: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS Array: AssociativeJS Array: AssociativeJS Array: AssociativeJS Array: Associative

• printing the whole array elements at once printing the whole array elements at once using joinusing join

Page 47: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS Array: AssociativeJS Array: AssociativeJS Array: AssociativeJS Array: Associative• printing the whole array elements at once printing the whole array elements at once

using joinusing join

Page 48: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript FunctionJavascript Function

• Functions in Javascript behave Functions in Javascript behave similar to numerous programming similar to numerous programming languages (C, C++, PHP, etc). languages (C, C++, PHP, etc).

• Put in head section or externalPut in head section or external• Variables inside a function is Variables inside a function is locallocal• Use Use returnreturn to return value and to return value and

exiting the function (return without exiting the function (return without value) without finishingvalue) without finishing

Page 49: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript FunctionsJavascript FunctionsInvolves two steps:Involves two steps:

• Define: Define: to define what processes should be takento define what processes should be taken

• Call/Invoke: Call/Invoke: to execute the functionsto execute the functions

Syntax of function definition:Syntax of function definition:

function function function_name function_name ((param1param1, param2, .., param_n, param2, .., param_n))

//parameters are optional//parameters are optional

{ {

//function’s code goes here//function’s code goes here

return return value_or_object; value_or_object; //optional//optional

}}

Involves two steps:Involves two steps:

• Define: Define: to define what processes should be takento define what processes should be taken

• Call/Invoke: Call/Invoke: to execute the functionsto execute the functions

Syntax of function definition:Syntax of function definition:

function function function_name function_name ((param1param1, param2, .., param_n, param2, .., param_n))

//parameters are optional//parameters are optional

{ {

//function’s code goes here//function’s code goes here

return return value_or_object; value_or_object; //optional//optional

}}

Page 50: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript function – Javascript function – activity activity 0909Javascript function – Javascript function – activity activity 0909

Page 51: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript Object – Javascript Object – activity activity 1010Javascript Object – Javascript Object – activity activity 1010

• Objects in Javascript can be created Objects in Javascript can be created directly using variable declaration ordirectly using variable declaration or

• Can be instantiated from an existing Can be instantiated from an existing classes classes

Page 52: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS object: directly JS object: directly instantiatedinstantiatedvar empty = {}; // An object with no propertiesvar empty = {}; // An object with no propertiesvar point = { x:0, y:0 };var point = { x:0, y:0 };var circle = { x:point.x, y:point.y+1, radius:2 };var circle = { x:point.x, y:point.y+1, radius:2 };var homer = {var homer = { "name": "Homer Simpson","name": "Homer Simpson", "age": 34,"age": 34, "married": true,"married": true, "occupation": "plant operator","occupation": "plant operator", 'email': "[email protected]"'email': "[email protected]"};};

Page 53: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS Object: directly instantiated JS Object: directly instantiated using varusing var

Page 54: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS: Creating classJS: Creating classfunction class_name (property_1, . . ., property_n) { this.property_1 = property_1 . . . this.property_n = property_n this.method_1 = method_name_1 . . . this.method_n = method_name_n}

function method_name_1() {}

function method_name_n() {}

function class_name (property_1, . . ., property_n) { this.property_1 = property_1 . . . this.property_n = property_n this.method_1 = method_name_1 . . . this.method_n = method_name_n}

function method_name_1() {}

function method_name_n() {}

Page 55: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS: Creating class – cont.JS: Creating class – cont.

Example:

function Person(aName,age) { this.name = aName; this.age = age; this.displayInfo = print;}

function print(){ window.alert(“Name= “ + this.name + “\nAge= “ + this.age);}

Example:

function Person(aName,age) { this.name = aName; this.age = age; this.displayInfo = print;}

function print(){ window.alert(“Name= “ + this.name + “\nAge= “ + this.age);}

Page 56: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS: Instantiating obj. from JS: Instantiating obj. from classclassobject_name = new class_name (property_1, property_2, …..);object_name = new class_name (property_1, property_2, …..);

Example:

// creating an object of class Person// creating an object of class Person

person1 = new Person(“Ali”,20);

// executing // executing displayInfo methodmethod

person1.displayInfo();

// changing property// changing property

person1.age=23;

Example:

// creating an object of class Person// creating an object of class Person

person1 = new Person(“Ali”,20);

// executing // executing displayInfo methodmethod

person1.displayInfo();

// changing property// changing property

person1.age=23;

Page 57: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS Object: Instantiating obj. JS Object: Instantiating obj. from classfrom class

Page 58: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS Object: Passing parameter JS Object: Passing parameter to object methodto object method

Page 59: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS Object: Passing parameter JS Object: Passing parameter to object method - continueto object method - continue

Page 60: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS Object: Member access JS Object: Member access using hash (associative) – using hash (associative) – activity 10.4activity 10.4

JS Object: Member access JS Object: Member access using hash (associative) – using hash (associative) – activity 10.4activity 10.4

•Access similar to associative array

•Accessing:•document.write(person1[‘name’]);•document.write(person1[‘age’]);

•Assignment•person1[‘name’] = “rosely”;

•Access similar to associative array

•Accessing:•document.write(person1[‘name’]);•document.write(person1[‘age’]);

•Assignment•person1[‘name’] = “rosely”;

Page 61: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS: Built-in objectsJS: Built-in objectsJS: Built-in objectsJS: Built-in objects

• DateDate– http://www.w3schools.com/js/js_obj_math.asphttp://www.w3schools.com/js/js_obj_math.asp

• StringString– http://www.w3schools.com/js/js_obj_string.asphttp://www.w3schools.com/js/js_obj_string.asp

• MathMath– http://www.w3schools.com/js/js_obj_date.asphttp://www.w3schools.com/js/js_obj_date.asp

• DateDate– http://www.w3schools.com/js/js_obj_math.asphttp://www.w3schools.com/js/js_obj_math.asp

• StringString– http://www.w3schools.com/js/js_obj_string.asphttp://www.w3schools.com/js/js_obj_string.asp

• MathMath– http://www.w3schools.com/js/js_obj_date.asphttp://www.w3schools.com/js/js_obj_date.asp

Page 62: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS: Built-in objects - DateJS: Built-in objects - Date

• The Date object is useful when you want The Date object is useful when you want to display a date or use a timestamp in to display a date or use a timestamp in some sort of calculation. some sort of calculation.

• You can either make a Date object by You can either make a Date object by supplying the date of your choice, supplying the date of your choice,

• or you can let Javascript create a Date or you can let Javascript create a Date object based on your visitor's system object based on your visitor's system clock. clock.

• It is usually best to let Javascript simply It is usually best to let Javascript simply use the system clock. use the system clock.

Page 63: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS: Built-in objects – DateJS: Built-in objects – Date- - activity 11activity 11• getTime()getTime() - Number of milliseconds since - Number of milliseconds since

1/1/1970 @ 12:00 AM 1/1/1970 @ 12:00 AM • getSeconds()getSeconds() - Number of seconds (0-59) - Number of seconds (0-59) • getMinutes()getMinutes() - Number of minutes (0-59) - Number of minutes (0-59) • getHours()getHours() - Number of hours (0-23) - Number of hours (0-23) • getDay()getDay() - Day of the week(0-6). 0 = - Day of the week(0-6). 0 =

Sunday, ... , 6 = Saturday Sunday, ... , 6 = Saturday • getDate()getDate() - Day of the month (0-31) - Day of the month (0-31) • getMonth()getMonth() - Number of month (0-11) - Number of month (0-11) • getFullYear()getFullYear() - The four digit year (1970- - The four digit year (1970-

9999) 9999)

Page 64: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS: Built-in objects - DateJS: Built-in objects - Date

Page 65: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS: Built-in objects - DateJS: Built-in objects - Date

• We check to see if We check to see if hourshours or or minutesminutes is less than 10, if it is then we need is less than 10, if it is then we need to add a zero to the beginning of to add a zero to the beginning of minutes. minutes.

• This is not necessary, but if it is 1:01 This is not necessary, but if it is 1:01 AM then our clock would output "1:1 AM then our clock would output "1:1 AM", which doesn't look very nice at AM", which doesn't look very nice at all! all!

Page 66: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript – Window & Javascript – Window & BoxesBoxes

– Popup WindowPopup Window– Alert message Alert message – Prompt (getting input)Prompt (getting input)– Confirm messageConfirm message– RedirectionRedirection

Page 67: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript: – Popup WindowJavascript: – Popup Window•window.open() – activity 12.1window.open() – activity 12.1

– Creates a new secondary browser Creates a new secondary browser window and loads the referenced window and loads the referenced resource. resource.

– window.open(window.open(strUrlstrUrl, , strWindowNamestrWindowName [, [, strWindowFeaturesstrWindowFeatures]); ]);

– strUrlstrUrl•This is the URL to be loaded in the newly This is the URL to be loaded in the newly

opened window. opened window. •strUrlstrUrl can be an HTML document on the can be an HTML document on the

web, web, • it can be an image file or any type of file it can be an image file or any type of file

which is supported by the browser. which is supported by the browser.

•window.open() – activity 12.1window.open() – activity 12.1– Creates a new secondary browser Creates a new secondary browser

window and loads the referenced window and loads the referenced resource. resource.

– window.open(window.open(strUrlstrUrl, , strWindowNamestrWindowName [, [, strWindowFeaturesstrWindowFeatures]); ]);

– strUrlstrUrl•This is the URL to be loaded in the newly This is the URL to be loaded in the newly

opened window. opened window. •strUrlstrUrl can be an HTML document on the can be an HTML document on the

web, web, • it can be an image file or any type of file it can be an image file or any type of file

which is supported by the browser. which is supported by the browser.

Page 68: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

Javascript: – Popup WindowJavascript: – Popup Window• strWindowFeaturesstrWindowFeatures

– dependentdependent - Subwindow closes if parent(the - Subwindow closes if parent(the window that opened it) window closes (window that opened it) window closes (yes/noyes/no))

– heightheight - The height of the new window, in pixels - The height of the new window, in pixels– widthwidth - The width of the new window, in pixels - The width of the new window, in pixels– leftleft - Pixel offset from the left side of the screen - Pixel offset from the left side of the screen– toptop - Pixel offset from the top of the screen - Pixel offset from the top of the screen– resizableresizable - Allow the user to resize the window - Allow the user to resize the window

or prevent resizing (or prevent resizing (yes/noyes/no) ) – statusstatus - Display the status bar or not ( - Display the status bar or not (yes/noyes/no))– scrollbarscrollbar ( (yes/noyes/no))

Page 69: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS: Alert - JS: Alert - activity 12.2activity 12.2

• Creating message boxCreating message box• No input, only Ok button to continueNo input, only Ok button to continue• Useful for debuggingUseful for debugging

– alert (“hello world”);alert (“hello world”);– var name = “rosely”;var name = “rosely”;– alert (“hello ” + name);alert (“hello ” + name);– var age = 17;var age = 17;– alert (“your age is: “ + age);alert (“your age is: “ + age);

• Creating message boxCreating message box• No input, only Ok button to continueNo input, only Ok button to continue• Useful for debuggingUseful for debugging

– alert (“hello world”);alert (“hello world”);– var name = “rosely”;var name = “rosely”;– alert (“hello ” + name);alert (“hello ” + name);– var age = 17;var age = 17;– alert (“your age is: “ + age);alert (“your age is: “ + age);

Page 70: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS: Prompt – JS: Prompt – activity 04activity 04JS: Prompt – JS: Prompt – activity 04activity 04

• Getting input from userGetting input from user– name = window.prompt ("Please enter your name", name = window.prompt ("Please enter your name",

“polan");“polan");

• Getting input from userGetting input from user– name = window.prompt ("Please enter your name", name = window.prompt ("Please enter your name",

“polan");“polan");

Page 71: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS: Confirm - JS: Confirm - activity 12.3activity 12.3

• Confirmation are most often used to Confirmation are most often used to confirmconfirm an important action that is an important action that is taking place on a website. taking place on a website.

• For example they may be about to For example they may be about to submit an order or about to visit a submit an order or about to visit a link that will take them away from link that will take them away from the current website. the current website.

Page 72: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:
Page 73: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS: Comment - JS: Comment - activity 12.4activity 12.4

• Same as Java/C++Same as Java/C++– // single line comment// single line comment

– /* /* – thisthis– isis– a multi line comment */a multi line comment */

• Same as Java/C++Same as Java/C++– // single line comment// single line comment

– /* /* – thisthis– isis– a multi line comment */a multi line comment */

Page 74: Javascript Browser – Client Side Processing Activity page/examples: rosely/js/ Browser – Client Side Processing Activity page/examples:

JS: Redirect - JS: Redirect - activity 12.5activity 12.5

• To send user to your new website To send user to your new website locationlocation

• In case of changing website In case of changing website address/doman address/doman