Topic5-JavaScript

advertisement
JavaScript (Introduction)
• Like C/C++ and Java, JavaScript is case sensitive
• It’s not Java
• Embedded inside HTML document
• 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>
How to create and run JavaScript function
from an external source…?
6
JavaScript Code Execution
Execute 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 Handler
Events:
• 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 Handler
Table of events and objects:
Event
Object
onClick
button
X
reset
X
submit
X
radio
X
checkbox
X
Link
X
Form
onSubmit
OnChange
onFocus
onBlur
onLoad
onUnload
onMouseOver
onSelect
X
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
Dynamic, no specific data type definition.
String and number are interchangeable.
var myName = "Pi";
myValue = 3.14159;
alert(myName);
myName = 3.14159
plus2pi = myName + myValue;
alert(plus2pi);
12
Variable
String Operations:
Concatenation
var firstName = "Hang";
var lastName = "Jee Fatt";
var fullName = firstName + " " + lastName;
alert(fullName);
13
Variable
String Operations:
String properties and methods
var fullName = "Hang Jee Fatt";
var length = fullName.length;
var abbr = fullName[0] + fullName[5] +
fullName[9];
alert(fullName + "\nLength: " + length +
"\nAbbreviative: " + abbr);
14
Variable
Numeric Operations:
Mostly are the same as implemented in C/C++,
Java, PHP, etc.
15
JavaScript Function
function plus2num(num1, num2) {
var result = num1 + num2;
return result;
}
How to apply this function in HTML document using a form…?
16
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 Model
window
Navigator
frame
String
history
location
Array
document
Date
image
anchor
applet
form
text
button
radio
area
link
select
reset
Math
submit
checkbox
textarea
password
hidden
file
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.value
document.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"
Do refer to www.w3schools.com for more string properties and methods.
29
Using Built-In Object Element (Math)
Math object properties & functions:
E
LN2
LN10
LOG2E
LOG10E
PI
SQRT1_2
SQRT2
abs
cos
min
tan
acos
eval
pow
toString
asin
exp
random
valueOf
atan
floor
round
atan2
log
sin
ceil
max
sqrt
Example: var result = Math.sqrt(16);
30
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 Object
Object 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() {
. . .
}
}
var objref = new object_name(. . .);
40
Creating New Object
Object literal (JSON):
var objref = {
property_1: value_1,
. . .,
property_n: value_n,
function_1: function(. . .) {
this.property_* = . . .;
. . .
}
. . .,
function_n: function(. . .) {
. . .
}, };
41
Creating New Object
JavaScript built-in Object() function:
var objref = new Object();
objref.property_1 = value_1;
. . .
objref.property_n = value_n;
objref.function_1 = function(. . .) {
this.property_* = . . .;
. . .
};
. . .
objref.function_n = function(. . .) {
. . .
};
42
Creating New Object
• Do notice that creating JavaScript object using
JSON literal or Object() built in function is
useful in the situation where the instance of
the object is needed to be dynamically
available during the runtime of the application
43
Querying Object Properties
Just 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>
44
Download