JavaScript (Introduction) Like C/C++ and Java, JavaScript is case sensitive It’s not Java Embedded...

Post on 21-Jan-2016

227 views 0 download

Transcript of JavaScript (Introduction) Like C/C++ and Java, JavaScript is case sensitive It’s not Java Embedded...

JavaScript (Introduction)

• Like C/C++ and Java, JavaScript is case sensitive

• It’s not Java

• Embedded inside HTML

• Browser dependent

• Interpreted language

• Loosely typed language

1

Basic JavaScript Code

<script> your javascript code is here </script>

2

Embedding JavaScript code inside HTML document

<html> <head> <title>js01</title> </head> <body> <script> alert("Hello, I'm from JavaScript") </script> </body> </html>

3

Load the JavaScript code from external source file

External source file name: myscript.js

External source file content:alert("Hello, I'm from JavaScript - external")

HTML file content:<html> <head> <title>js01</title> </head> <body> <script src="myscript.js"> </script> </body> </html>

4

JavaScript Code Execution • Automatically when the page is loaded (previous

examples)

• Write JavaScript code as function and execute via event handler

<html> <head> <title>js02</title> <script> function hello() {     alert("Hello, I'm JavaScript function") } </script> </head> <body> </body> </html>

5

JavaScript Code Execution

Execute JavaScript function using onload event:

<html> <head> <title>js02</title> . . . </head> <body onload="hello();"> </body> </html>

6

How to create and run JavaScript function from an external source…?

JavaScript Code ExecutionExecute JavaScript function via user actions:

<html> <head> <title>js02</title> . . . </head> <body> <a href="javascript:hello();"> Clik me (hypertext link) </a> <form onsubmit=“hello();”> <input type="submit" value="Click me” onclick="hello();"> </form> </body> </html>

7

Event HandlerEvents:

• Auto triggered by the system - when the browser loading a new page (onload event)

• User action - when the user click a button (onclick event)

8

Event HandlerTable of events and objects:  Event

Object onClick onSubmit OnChange onFocus onBlur onLoad onUnload onMouseOver onSelect

button X                

reset X                

submit X                

radio X                

checkbox X                

Link X             X  

Form   X              

Text     X X X       X

textarea     X X X       X

select     X X X        

window           X X    

9

Debugging JavaScript Code

• Firefox: Tools > Web Developer > Web Console(Ctrl + Shift + K)

• Chrome:Tools > JavaScript Console(Ctrl + Shift + I)

10

JavaScript Keywords

if else while  for break

continue true false null return

int var in with this

function new      

11

Variable

var myName = "Pi";myValue = 3.14159;

alert(myName);

myName = 3.14159plus2pi = myName + myValue;

alert(plus2pi);

12

Dynamic, no specific data type definition. String and number are interchangeable.

Variable

var firstName = "Hang";var lastName = "Jee Fatt";var fullName = firstName + " " + lastName;

alert(fullName);

13

String Operations:

Concatenation

Variable

var fullName = "Hang Jee Fatt";

var length = fullName.length;var abbr = fullName[0] + fullName[5] + fullName[9];

alert(fullName + "\nLength: " + length + "\nAbbreviative: " + abbr);

14

String Operations:

String properties and methods

Variable

15

Numeric Operations:

Mostly are the same as implemented in C/C++, Java, PHP, etc.

JavaScript Function

function plus2num(num1, num2) { var result = num1 + num2; return result;}

16

How to apply this function in HTML document with a form…?

Document Object Model (DOM)

• programming interface for HTML and XML documents

• In the beginning, JavaScript and the DOM were tightly intertwined, but eventually they evolved into separate entities

• JavaScript acting as a tools/language to communicate with the interface

• DOM designed to be independent of any particular programming language

• It’s possible to communicate with DOM using other languages such as VBScript, Python, Perl, etc.

17

HTML DOM Elements

• element• window• document• event• style• range• selection

18

HTML DOM Modelwindow

history

frame

location

Navigator

String

document

image

Array

Date

Math

applet

anchor

form

area

link

button

radio

text

reset

select

checkbox

submit

password

textarea

file

hidden

19

Accessing HTML Object Elements

object_ref.object_property object_ref.object_method

20

Accessing HTML Object Elements (Methods/Properties)

for (property in object_ref) { alert(property + " = " + object_ref[property]);}

21

Accessing HTML Object Elements (Methods/Properties)

<form name="my_form" method="POST"><span id= "caption">Input Data</span> <input type="text" name="ic" id="ic" size=15></form>

To access the value of the “IC” input field, use either one of the statements below:

document.my_form.ic.valuedocument.getElementById('ic').value

22

Accessing HTML Object Elements (Methods/Properties)

<form name="my_form" method="POST"><span id= "caption">Input Data</span> <input type="text" name="ic" id="ic" size=15></form>

The CSS and inner content of HTML tag.

var caption = document.getElementById('caption');

caption.style.fontWeight = "bold";caption.innerHTML = 'Name';

23

Manipulating HTML Object Elements (document & window)

Write content into HTML document:

document.open();document.write("<pre>\n");document.write("Hello World\n");document.writeln("How are You?");document.write("World: I'm fine\n");document.write("<pre>");document.close() ;

24

Manipulating HTML Object Elements (document & window)

Open and write/set content into new browser window:

newWin = window.open("URL", "windowName",

["windowAttributes"]) ;

25

Manipulating HTML Object Elements (document & window)

Open and write/set content into new browser Window (example):

newWin = window.open("", "myWindwow", "width=400,height=300");

newWin.document.open() ;newWin.document.write("Hello I’m new window");newWin.document.close() ;

26

Manipulating HTML Object Elements (document & window)

Print out client browser info.:

document.open()document.writeln("<pre>")document.writeln("<b>navigator.appCodeName = </b>" + navigator.appCodeName)document.writeln("<b>navigator.appName = </b>" + navigator.appName)document.writeln("<b>navigator.appVersion = </b>" + navigator.appVersion)document.writeln("<b>navigator.mimeTypes.length = </b>" + navigator.mimeTypes.length)document.writeln("<b>navigator.mimeTypes[0].type = </b>" + navigator.mimeTypes[0].type)document.writeln("<b>navigator.mimeTypes[0].description = </b>" + navigator.mimeTypes[0].description)document.writeln("<b>navigator.mimeTypes[0].suffixes = </b>" + navigator.mimeTypes[0].suffixes)document.writeln("<b>navigator.userAgent = </b>" + navigator.userAgent)document.writeln("</pre>")document.close()

27

Using Built-In Object Element (Date)

var today = new Date();document.open();

document.write("<p>" + today + "<p>\n");

document.write("<p>Today (dd/mm/yyyy) is: " + today.getDate() + "/" + (today.getMonth() + 1) + "/" + (today.getFullYear()) + "</p>\n");

document.close();

28

Using Built-In Object Element (String)

String handling functions (var str = "Hello World"):

Method Description Example

charAt(pos) Return the character at the specified index.

str.charAt(0) return a value of "H"

indexOf(searchText[, startPos])

Return the index of the first occurrence of searchText.

str.indexOf("or") return a value of 7

lastIndexOf(searchText[, startPos])

Return the index of the last occurrence of searchText.

str.lastIndexOf("l") return a value of 9

substring(startPos, endPos) Return the substring of the string starting at startPos and ending at endPos

str.substring(6, 8) return a value of "Wor"

29

Do refer to www.w3schools.com for more string properties and methods.

Using Built-In Object Element (Math)

Math object properties & functions:E LN10 LOG10E SQRT1_2

LN2 LOG2E PI SQRT2

abs cos min tan

acos eval pow toString

asin exp random valueOf

atan floor round  

atan2 log sin  

ceil max sqrt  

30

Example: var result = Math.sqrt(16);

Using Built-In Object Element (Array)

Define array variable using Array object:

var months = new Array()months[0] = "Jan"months[1] = "Feb". . .. . .months[11] = "Dec”;

31

Using Built-In Object Element (Array)

Define array variable using Array object:

var days = new Array("Sunday", "Monday", "Tuesday", "Wednesday",

"Thursday", "Friday",

"Saturday");

32

Using Built-In Object Element (Array)

Define array variable using Array object:

var dayOfAug = new Array(31);

for (var i = 0; i < dayOfAug.length; i++) { dateOfAugust[i] = i + 1}

33

Using Built-In Object Element (Array)

Array object can be used to store almost everything that exist as primitive or object in JavaScript.

var items = new Array;

items.push("string1");items.push(new String("string2"));items.push(Math.PI);items.push(new Date());

var output = "";for (idx in items) { output += items[idx] + "<br />";} 34

Using Built-In Object Element (Array)

Reference to Array item is not limited by integer index value, but also be possible by unique key string value.

var month2num = new Array;month2num["Jan"] = 1;month2num["Feb"] = 2;month2num["Mar"] = 3;

var output = "";for (key in month2num) { output += key + " = " + month2num[key] + "<br />";} 35

HTML DOM (Nodes)HTML objects are standard HTML tags used inside the HTML document Each of these objects can have child/sub objects that are referred as nodes in JavaScript It’s possible to dynamically append, navigate, and remove nodes by using JavaScript

36

HTML DOM (Nodes)

Append Child Node:

<ul id="ulist"></ul>

<script>var list = document.getElementById("ulist");var item = document.createElement("li");item.id="item_1";item.innerHTML = "Apple";list.appendChild(item);</script>

37

HTML DOM (Nodes)

Remove Child Node:

<ul id="ulist"> <li id="item_1">Apple</li> <li id="item_2">Grape</li> <li id="item_3">Orange</li></ul>

<script>var list = document.getElementById("ulist");var item = document.getElementById("item_2");list.removeChild(item); </script>

38

HTML DOM (Nodes)Navigate Child Node:

<ul id="ulist"> <li id="item_1">Apple</li> <li id="item_3">Orange</li></ul><pre id="list_data"></pre>

<script>var list = document.getElementById("ulist");var item = list.firstChild;var pre = document.getElementById("list_data");

while (item) { pre.innerHTML += item + "=" + item.innerHTML + "\n"; item = item.nextSibling;}</script>

39

Creating New ObjectObject literal (JSON):

object_ref = { property_1:value_1, . . ., property_n:value_n };

JavaScript built-in Object() function:

object_ref = new Object();object_ref.property_1 = "value_1";. . .object_ref.property_n = "value_n";

40

Creating New ObjectObject constructor:

function object_name (arg_1, . . ., arg_n) { this.property_1 = arg_1; . . . this.property_n = arg_n;

this.method_1 = method_name_1; function method_name_1() { . . . } . . . this.method_n = method_name_n; function method_name_n() { . . . }}

41

Querying Object PropertiesJust like array with unique key string index

<script>var mark = { project:45, lab:15, final:20 };

var total = 0;

for (property in mark) { total += parseInt(mark[property]);}</script>

42