SlideShare a Scribd company logo
1 of 87
Download to read offline
Chapter 3
Introduction to Javascript
Lectured by:
Nguyễn Hữu Hiếu
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
2
JavaScript
n JavaScript is the programming language of HTML
and the Web.
n Programming makes computers do what you want
them to do. JavaScript is easy to learn.
n This tutorial will teach you JavaScript from basic to
advanced.
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
3
Why Study JavaScript?
n JavaScript is one of the 3 languages all web
developers must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behaviour of web
pages
n This lecture is about JavaScript, and how
JavaScript works with HTML and CSS.
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
4
JavaScript Introduction
n JavaScript Can Change HTML Content
One of many HTML methods is getElementById().
n This example uses the method to "find" an HTML
element (with id="demo"), and changes the
element content (innerHTML) to "Hello JavaScript”:
document.getElementById("demo").innerHTML
= "Hello JavaScript”;
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
5
Example
<!DOCTYPE html>
<html>
<body>
<h1>What Can JavaScript Do?</h1>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button"
onclick="document.getElementById('demo').innerHTML =
'Hello JavaScript!'">
Click Me!
</button>
</body>
</html>
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
6
JavaScript Can Change HTML Attributes
This example changes an HTML image, by changing the src attribute of an
<img> tag:
<!DOCTYPE html><html>
<body>
<h1>JavaScript Can Change Images</h1>
<img id="myImage" onclick="changeImage()" src="pic_bulboff.gif" width="100"
height="180”>
<p>Click the light bulb to turn on/off the light.</p>
<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("bulbon")) {
image.src = "pic_bulboff.gif"; } else {
image.src = "pic_bulbon.gif"; }
}
</script>
</body> </html>
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
7
JavaScript Can Change HTML Styles (CSS)
<!DOCTYPE html>
<html>
<body>
<h1>What Can JavaScript Do?</h1>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<script>
function myFunction() {
var x = document.getElementById("demo");
x.style.fontSize = "25px";
x.style.color = "red";
}
</script>
<button type="button" onclick="myFunction()">Click Me!</button>
</body>
</html>
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
8
JavaScript Can Validate Data
n JavaScript is often used to validate input
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
9
Did You Know?
n JavaScript and Java are completely different
languages, both in concept and design.
n JavaScript was invented by Brendan Eich in 1995,
and became an ECMA standard in 1997.
n ECMA-262 is the official name. ECMAScript 5
(JavaScript 1.8.5 - July 2010) is the current
standard
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
10
JavaScript Where To
n JavaScript can be placed in the <body> and the
<head> sections of an HTML page.
n The <script> Tag In HTML, JavaScript code must
be inserted between <script> and </script> tag
<script>
document.getElementById("demo").innerHTML = "My First JavaScript”;
</script>
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
11
JavaScript Functions and Events
n A JavaScript function is a block of JavaScript code,
that can be executed when "asked" for.
n For example, a function can be executed when an
event occurs, like when the user clicks a button.
n You will learn much more about functions and
events in later chapters.
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
12
JavaScript in <head> or <body>
n You can place any number of scripts in an HTML
document.
n Scripts can be placed in the <body>, or in the
<head> section of an HTML page, or in both.
n Keeping all code in one place, is always a good
habit.
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
13
JavaScript in <head>
n In this example, a JavaScript function is placed in
the <head> section of an HTML page.
n The function is invoked (called) when a button is
clicked:
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
14
Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph
changed."; }
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
15
JavaScript in <body>
n In this example, a JavaScript function is placed in
the <body> section of an HTML page.
n The function is invoked (called) when a button is
clicked:
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
16
Example
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph
changed."; }
</script>
</body>
</html>
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
17
External JavaScript
n Scripts can also be placed in external files.
n External scripts are practical when the same code is used in
many different web pages.
n JavaScript files have the file extension .js.
To use an external script, put the name of the script file in
the src (source)
n attribute of the <script> tag:
<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
18
External JavaScript
n You can place an external script reference in <head> or
<body> as you like.
n The script will behave as if it was located exactly where the
<script> tag is located.
n External scripts cannot contain <script> tags.
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
19
External JavaScript Advantages
n Placing JavaScripts in external files has some
advantages:
n It separates HTML and code
n It makes HTML and JavaScript easier to read and
maintain
n Cached JavaScript files can speed up page loads
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
20
JavaScript Output
n JavaScript does not have any built-in print or display
functions.
n JavaScript Display Possibilities JavaScript can "display" data
in different ways:
1. Writing into an alert box, using window.alert().
2. Writing into the HTML output using document.write().
3. Writing into an HTML element, using innerHTML.
4. Writing into the browser console, using console.log().
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
21
Using window.alert()
You can use an alert box to display:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
22
Using document.write()
For testing purposes, it is convenient to use document.write():
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
23
Using document.write()
Using document.write() after an HTML document is
fully loaded, will delete all existing HTML:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button onclick="document.write(5 + 6)">Try it</button>
</body>
</html>
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
24
Using innerHTML
n To access an HTML element, JavaScript can use
the document.getElementById(id) method.
n The id attribute defines the HTML element. The
innerHTML property defines the HTML content:
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
25
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
26
Using console.log()
n In your browser, you can use the console.log()
method to display data.
n Activate the browser console with F12, and select
"Console" in the menu.
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
27
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
console.log(5 + 6);
</script>
</body>
</html>
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
28
JavaScript Syntax
n JavaScript syntax is the set of rules, how
JavaScript programs are constructed.
n A computer program is a list of "instructions" to be
"executed" by the computer.
n In a programming language, these program
instructions are called statements.
n JavaScript is a programming language.
JavaScript statements are separated by semicolon.
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
29
Example
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Statements</h1>
<p>Statements are separated by semicolons.</p>
<p>The variables x, y, and z are assigned the values 5, 6, and 11:</p>
<p id="demo"></p>
<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>
</body>
</html>
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
30
JavaScript Statements
n JavaScript statements are composed of:
n Values.
n Operators.
n Expressions.
n Keywords.
n Comments.
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
31
1-JavaScript Values
n The JavaScript syntax defines two types of values:
Fixed values and variable values.
n 1.1-Fixed values are called literals.
n 2.1-Variable values are called variables.
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
32
1.1-JavaScript Literals
n The most important rules for writing fixed values are:
n Numbers are written with or without decimals:
n 10.50
n 1001
n Strings are text, written within double or single quotes:
n "John Doe”
n 'John Doe’
n Expressions can also represent fixed values:
n 5+6
n 5 * 10
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
33
1.2-JavaScript Variables
n In a programming language, variables are used to
store data values.
n JavaScript uses the var keyword to define
variables.
An equal sign is used to assign values to variables.
n In this example, x is defined as a variable. Then, x
is assigned (given) the value 6:
n var x;
n x = 6;
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
34
2-JavaScript Operators
n JavaScript uses an assignment operator ( = ) to
assign values to variables:
n var x = 5;
n var y = 6;
n JavaScript uses arithmetic operators ( + - * / ) to
compute values: (5 + 6) * 10
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
35
Object literals
35
n You don’t declare the types of variables in JavaScript
n JavaScript has object literals, written with this syntax:
n { name1 : value1 , ... , nameN : valueN }
n Example (from Netscape’s documentation):
n car = {myCar: "Saturn", 7: "Mazda",
getCar: CarTypes("Honda"), special: Sales}
n The fields are myCar, getCar, 7 (this is a legal field name) , and
special
n "Saturn" and "Mazda" are Strings
n CarTypes is a function call
n Sales is a variable you defined earlier
n Example use: document.write("I own a " + car.myCar);
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
36
Three ways to create an object
36
n You can use an object literal:
n var course = { number: "CIT597", teacher: "Dr. Dave" }
n You can use new to create a “blank” object, and add fields
to it later:
n var course = new Object();
course.number = "CIT597";
course.teacher = "Dr. Dave";
n You can write and use a constructor:
n function Course(n, t) { // best placed in <head>
this.number = n; // keyword "this" is required, not optional
this.teacher = t;
}
n var course = new Course("CIT597", "Dr. Dave");
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
37
Array literals
37
n You don’t declare the types of variables in JavaScript
n JavaScript has array literals, written with brackets and
commas
n Example: color = ["red", "yellow", "green", "blue"];
n Arrays are zero-based: color[0] is "red"
n If you put two commas in a row, the array has an “empty”
element in that location
n Example: color = ["red", , , "green", "blue"];
n color has 5 elements
n However, a single comma at the end is ignored
n Example: color = ["red", , , "green", "blue”,]; still has 5
elements
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
38
Four ways to create an array
38
n You can use an array literal:
var colors = ["red", "green", "blue"];
n You can use new Array() to create an empty array:
n var colors = new Array();
n You can add elements to the array later:
colors[0] = "red"; colors[2] = "blue"; colors[1]="green";
n You can use new Array(n) with a single numeric
argument to create an array of that size
n var colors = new Array(3);
n You can use new Array(…) with two or more
arguments to create an array containing those
values:
n var colors = new Array("red","green", "blue");
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
39
The length of an array
39
n If myArray is an array, its length is given by
myArray.length
n Array length can be changed by assignment beyond
the current length
n Example: var myArray = new Array(5); myArray[10] = 3;
n Arrays are sparse, that is, space is only allocated for
elements that have been assigned a value
n Example: myArray[50000] = 3; is perfectly OK
n But indices must be between 0 and 232-1
n As in C and Java, there are no two-dimensional arrays;
but you can have an array of arrays: myArray[5][3]
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
40
Arrays and objects
40
n Arrays are objects
n car = { myCar: "Saturn", 7: "Mazda" }
n car[7] is the same as car.7
n car.myCar is the same as car["myCar"]
n If you know the name of a property, you can use dot
notation: car.myCar
n If you don’t know the name of a property, but you have it
in a variable (or can compute it), you must use array
notation: car["my" + "Car"]
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
41
Array functions
41
n If myArray is an array,
n myArray.sort() sorts the array alphabetically
n myArray.sort(function(a, b) { return a - b; }) sorts numerically
n myArray.reverse() reverses the array elements
n myArray.push(…) adds any number of new elements to the end of
the array, and increases the array’s length
n myArray.pop() removes and returns the last element of the array,
and decrements the array’s length
n myArray.toString() returns a string containing the values of the
array elements, separated by commas
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
42
The for…in statement
42
n You can loop through all the properties of an object with
for (variable in object) statement;
n Example: for (var prop in course) {
document.write(prop + ": " + course[prop]);
}
n Possible output: teacher: Dr. Dave
number: CIT597
n The properties are accessed in an undefined order
n If you add or delete properties of the object within the loop, it is
undefined whether the loop will visit those properties
n Arrays are objects; applied to an array, for…in will visit the
“properties” 0, 1, 2, …
n Notice that course["teacher"] is equivalent to course.teacher
n You must use brackets if the property name is in a variable
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
43
3-JavaScript Keywords
n JavaScript keywords are used to identify
actions to be performed.
n The var keyword tells the browser to create
a new variable:
n var x = 5 + 6;
n var y = x * 10;
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
44
4-JavaScript Comments
n Not all JavaScript statements are "executed".
n Code after double slashes // or between /* and */ is
n treated as a comment.
n Comments are ignored, and will not be executed:
var x = 5; // I will be executed
// var x = 6; I will NOT be executed
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
45
JavaScript is Case Sensitive
n All JavaScript identifiers are case sensitive.
The variables lastName and lastname, are two different
variables.
lastName = "Doe”;
lastname = “Peterson";
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
46
JavaScript and Camel Case
n Historically, programmers have used three ways of joining
multiple words into one variable name:
n Hyphens:
n first-name, last-name, master-card, inter-city.
n Underscore:
n first_name, last_name, master_card, inter_city.
n Camel Case:
n FirstName, LastName, MasterCard, InterCity.
n Hyphens are not allowed in JavaScript. It is reserved for
subtractions.
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
47
JavaScript Statements
n In HTML, JavaScript statements are "instructions" to be
"executed" by the web browser.
n This statement tells the browser to write "Hello Dolly."
inside an HTML element with id="demo":
n Example:
document.getElementById("demo").innerHTML = "Hello Dolly.”;
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
48
JavaScript Programs
n Most JavaScript programs contain many JavaScript
statements.
n The statements are executed, one by one, in the same
order as they are written.
n In this example, x, y, and z is given values, and finally z is
displayed: Example:
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML = z;
n JavaScript programs (and JavaScript statements) are often
called JavaScript code.
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
49
Semicolons ;
n Semicolons separate JavaScript statements.
n Add a semicolon at the end of each executable statement:
a = 5;
b = 6;
c = a + b;
When separated by semicolons, multiple statements on one line are
allowed: a = 5; b = 6; c = a + b;
n On the web, you might see examples without semicolons.
Ending statements with semicolon is not required, but
highly recommended.
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
50
JavaScript White Space
n JavaScript ignores multiple spaces. You can add white
space to your script to make it more readable.
n The following lines are equivalent: var person = "Hege";
var person=“Hege”;
n A good practice is to put spaces around operators ( = + - *
/ ):
var x = y + z;
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
51
JavaScript Line Length and Line Breaks
n For best readability, programmers often like to avoid code
lines longer than 80 characters. If a JavaScript statement
does not fit on one line, the best place to break it, is after an
operator:
document.getElementById("demo").innerHTML = "Hello
Dolly.”;
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
52
JavaScript Code Blocks
n JavaScript statements can be grouped together in code
blocks, inside curly brackets {...}.
n The purpose of code blocks this is to define statements to
be executed together.
n One place you will find statements grouped together in
blocks, are in JavaScript functions:
function myFunction() {
document.getElementById("demo").innerHTML = "Hello Dolly.";
document.getElementById("myDIV").innerHTML = "How are you?";
}
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
53
JavaScript Keywords
n JavaScript statements often start with a keyword to identify
the JavaScript action to be performed.
n Here is a list of some of the keywords you will learn about
in this lecture:
n JavaScript keywords are reserved words. Reserved words
cannot be used as names for variables.
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
54
JavaScript Keywords
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
55
Value = undefined
n In computer programs, variables are often declared without
a value. The value can be something that has to be
calculated, or something that will be provided later, like
user input.
n A variable declared without a value will have the value
undefined. The variable carName will have the value
undefined after the execution of this statement:
n Example
var carName;
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
56
Control Structures
n There are three basic types of control structures in
JavaScript: the if statement, the while loop, and the
for loop
n Each control structure manipulates a block of JavaScript
expressions beginning with { and ending with }
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
57
The If Statement
If ( x = = 10)
{ y = x*x;
}
else
{ x = 0;
}
n The if statement
allows JavaScript
programmers to a
make decision
n Use an if
statement whenever
you come to a “fork”
in the program
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
58
Repeat Loops
n A repeat loop is a group of statements that is repeated until
a specified condition is met
n Repeat loops are very powerful programming tools; They
allow for more efficient program design and are ideally
suited for working with arrays
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
59
The While Loop
count = 0;
while (count <= 10) {
document.write(count);
count++;
}
n The while loop is
used to execute a
block of code while
a certain condition
is true
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
60
The For Loop
n The for loop is used when there is a need to have a
counter of some kind
n The counter is initialized before the loop starts, tested after
each iteration to see if it is below a target value, and finally
updated at the end of the loop
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
61
Example: For Loop
i=1 initializes the counter
i<=10 is the target
value
i++ updates the
counter at the end
of the loop
// Print the numbers 1
through 10
for (i=1; i<= 10; i++)
document.write(i);
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
62
Example: For Loop
<SCRIPT>
for (i=1; i<=5; i++) {
document.write(i);
}
</SCRIPT>
<SCRIPT>
document.write("1");
document.write("2");
document.write("3");
document.write("4");
document.write("5");
</SCRIPT>
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
63
Functions
n Functions are a collection of JavaScript statement that
performs a specified task
n Functions are used whenever it is necessary to repeat an
operation
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
64
Functions
n Functions have inputs and outputs
n The inputs are passed into the function and are known as
arguments or parameters
n Think of a function as a “black box” which performs an
operation
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
65
Defining Functions
n The most common way to define a function is with the
function statement.
n The function statement consists of the function keyword
followed by the name of the function, a comma-separated
list of parameter names in parentheses, and the statements
which contain the body of the function enclosed in curly
braces
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
66
Example: Function
Name of Function:
square
Input/Argument: x
Output: x*x
function square(x) {
return x*x;
}
z = 3;
sqr_z = square(z);
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
67
Example: Function
function sum_of_squares(num1,num2) {
return (num1*num1) + (num2*num2);
}
function sum_of_squares(num1,num2) {
return (square(num1) + square(num2));
}
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
68
Javscript Events
68
n Events are actions that can be detected by Javascript
n Every element on a web page has certain events which can
trigger Javascript functions
n Often placed within the HTML tag
n <tag attribute1 attribute2 onEventName="javascript code;">
n <a href="" onMouseOver="popupFunc();">
n The set of all events which may occur and the page
elements on which they can occur is part of the Document
Object Model(DOM) not Javascript
n Browsers don’t necessarily share the same set of events
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
69
Common Javascript Events
69
Event Occurs when... Event Handler
n click User clicks on form element or link onClick
n change User changes value of text, textarea, or select element onChange
n focus User gives form element input focus onFocus
n blur User removes input focus from form element onBlur
n mouseover User moves mouse pointer over a link or anchor onMouseOver
n mouseout User moves mouse pointer off of link or anchor onMouseOut
n select User selects form element's input field onSelect
n submit User submits a form onSubmit
n resize User resizes the browser window onResize
n load User loads the page in the Navigator onLoad
n unload User exits the page onUnload
5.2 DOM (Document Object Model)
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
71
The Document Object Model
71
n When a document is loaded in the web browser, a number
of objects are created.
n Most commonly used are window and document
n Window
n open(), close(), alert(), confirm(), prompt()
n Document
n Contains arrays which store all the components of your page
n You can access and call methods on the components using the
arrays
n An object may also be accessed by its name
n document.myform.address.value = “123 Main”
n document.myform.reset()
n Can also search for element by name or id
n document.getElementById(“myelementid”)
n document.getElementsByName(“myelementname”)
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
72
DOM & DHTML
n Dynamic web pages with JavaScript and DOM
n DHTML (Dynamic HTML)
n DOM nodes and DOM tree
n Traversing, editing and modifying DOM nodes
n Editing text nodes
n Accessing, editing and modifying elements'
attributes
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
73
DOM Concept
n DOM makes all components of a web page accessible
n HTML elements
n their attributes
n text
n They can be created, modified and removed with
JavaScript
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
74
DOM Objects
n DOM components are accessible as objects or
collections of objects
n DOM components form a tree of nodes
• relationship parent node – children nodes
• document is the root node
n Attributes of elements are accessible as text
n Browsers can show DOM visually as an
expandable tree
n Firebug for Firefox
n in IE -> Tools -> Developer Tools
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
75
DOM Standards
n W3C www.w3.org defines the standards
n DOM Level 3 recommendation
n www.w3.org/TR/DOM-Level-3-Core/
n DOM Level 2 HTML Specification
n www.w3.org/TR/DOM-Level-2-HTML/
n additional DOM functionality specific to HTML, in
particular objects for XHTML elements
n But, the developers of web browsers
n don't implement all standards
n implement some standards differently
n implement some additional features
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
76
Accessing Nodes by id
n Access to elements by their id
n document.getElementById(<id>)
n returns the element with id <id>
n id attribute can be defined in each start tag
n div element with id attribute can be used as an root node for
a dynamic DOM subtree
n span element with id attribute can be used as a dynamic inline
element
n The preferred way to access elements
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
77
Other Access Methods
n Access by elements' tag
n there are typically several elements with the same tag
n document.getElementsByTagName(<tag>)
n returns the collection of all elements whose tag is <tag>
n the collection has a length attribute
n an item in the collection can be reached by its index
n e.g.
n var html = document.getElementsByTagName("html")[0];
n Access by elements' name attribute
n several elements can have the same name
n document.getElementsByName(<name>)
n returns the collection of elements with name <name>
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
78
Traversing DOM tree
n Traversal through node properties
n childNodes property
n the value is a collection of nodes
n has a length attribute
n an item can be reached by its index
n e.g. var body = html.childNodes[1];
n firstChild, lastChild properties
n nextSibling, previousSibling properties
n parentNode property
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
79
Other Node Properties
• nodeType property
n ELEMENT_NODE: HTML element
n TEXT_NODE: text within a parent element
n ATTRIBUTE_NODE: an attribute of a parent element
n attributes can be accessed another way
n CDATA_SECTION_NODE
n CDATA sections are good for unformatted text
n nodeName property
n nodeValue property
n attributes property
n innerHTML property
n not standard, but implemented in major browsers
n very useful
n style property
n object whose properties are all style attributes, e.g., those defied in CSS
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
80
Accessing JS Object's Properties
n There are two different syntax forms to access
object's properties in JS (
n <object>.<property>
n dot notation, e.g., document.nodeType
n <object>[<property-name> ]
n brackets notation, e.g., document["nodeType"]
n this is used in for-in loops
n this works for properties of DOM objects, too
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
81
Attributes of Elements
• Access through attributes property
n attributes is an array
n has a length attribute
n an item can be reached by its index
n an item has the properties name and value
n e.g.
n var src = document.images[0].attributes[0].value;
n Access through function getAttribute(<name>)
n returns the value of attribute <name>
n e.g.
n var src = document.images[0].getAttribute("src");
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
82
Text Nodes
n Text node
n can only be as a leaf in DOM tree
n it’s nodeValue property holds the text
n innerHTML can be used to access the text
n Watch out:
n There are many more text nodes than you would expect!
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
83
Modifying DOM Structure
n document.createElement(<tag>)
n creates a new DOM element node, with <tag> tag.
n the node still needs to be inserted into the DOM tree
n document.createTextNode(<text>)
n creates a new DOM text with <text>
n the node still needs to be inserted into the DOM tree
n <parent>.appendChild(<child>)
n inserts <child> node behind all existing children of <parent> node
n <parent>.insertBefore(<child>,<before>)
n inserts <child> node before <before> child within <parent> node
n <parent>.replaceChild(<child>,<instead>)
n replaces <instead> child by <child> node within <parent> node
n <parent>.removeChild(<child>)
n removes <child> node from within <parent> node
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
84
Modifying Node Attributes
n <node>.setAttribute(<name>,<value>)
n sets the value of attribute <name> to <value>
n e.g.
n document.images[0].setAttribute("src","keiki.jpg");
n That's the standard
n but it doesn't work in IE, there you have to use
n setAttribute(<name=value>)
n e.g.
n document.images[0].setAttribute("src="keiki.jpg"");
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
85
W3C Document Object Model
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
86
Special DOM Objects
n window
n the browser window
n new popup windows can be opened
n document
n the current web page inside the window
n body
n <body> element of the document
n history
n sites that the user visited
n makes it possible to go back and forth using scripts
n location
n URL of the document
n setting it goes to another page
Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
© 2017
Lập Trình Web
87
Tài Liệu Tham Khảo
n [1] Stepp,Miller,Kirst. Web Programming Step by Step.( 1st
Edition, 2009) Companion Website:
http://www.webstepbook.com/
n [2] W3Schools,
http://www.w3schools.com/html/default.asp

More Related Content

Similar to Chapter 3 - Introduction to Javascript (1).pdf

Php cơ bản của trung tâm hocweb.com.vn
Php cơ bản của trung tâm hocweb.com.vnPhp cơ bản của trung tâm hocweb.com.vn
Php cơ bản của trung tâm hocweb.com.vnDang le Nam
 
Asp.net mvc 3 (c#) (9 tutorials) egroups vn
Asp.net mvc 3 (c#) (9 tutorials)   egroups vnAsp.net mvc 3 (c#) (9 tutorials)   egroups vn
Asp.net mvc 3 (c#) (9 tutorials) egroups vnNguyen Van Hung
 
Ebook học Javascript cơ bản tới nâng cao
Ebook học Javascript cơ bản tới nâng caoEbook học Javascript cơ bản tới nâng cao
Ebook học Javascript cơ bản tới nâng caoTrung Thanh Nguyen
 
Java script dh bk share-book.com
Java script dh bk   share-book.comJava script dh bk   share-book.com
Java script dh bk share-book.comphongbk1609
 
Cq lt hdt-th2011-02-tuan04
Cq lt hdt-th2011-02-tuan04Cq lt hdt-th2011-02-tuan04
Cq lt hdt-th2011-02-tuan04. .
 
Giao trinh java_script (1)
Giao trinh java_script (1)Giao trinh java_script (1)
Giao trinh java_script (1)duynamit
 
Session 08 Final
Session 08 FinalSession 08 Final
Session 08 FinalSamQuiDaiBo
 
JavaScript (Tieng viet)
JavaScript (Tieng viet)JavaScript (Tieng viet)
JavaScript (Tieng viet)Park Ji Hưng
 
Giao trinh java_script
Giao trinh java_scriptGiao trinh java_script
Giao trinh java_scriptnmphuong91
 
Bài 4: JSP Cơ Bản - Lập Trình Mạng Nâng Cao
Bài 4: JSP Cơ Bản - Lập Trình Mạng Nâng CaoBài 4: JSP Cơ Bản - Lập Trình Mạng Nâng Cao
Bài 4: JSP Cơ Bản - Lập Trình Mạng Nâng CaoTuan Nguyen
 
Convert psd to html5
Convert psd to html5Convert psd to html5
Convert psd to html5Tien Van
 
Convert psd to html5 nhất nghệ - hoclaptrinhweb.com
Convert psd to html5 nhất nghệ - hoclaptrinhweb.comConvert psd to html5 nhất nghệ - hoclaptrinhweb.com
Convert psd to html5 nhất nghệ - hoclaptrinhweb.comMasterCode.vn
 
Tự học JavaScript
Tự học JavaScriptTự học JavaScript
Tự học JavaScriptÁnh Nguyễn
 
Tu hoc javascript
Tu hoc javascriptTu hoc javascript
Tu hoc javascriptzingoncmu2
 
Convert psd to html5
Convert psd to html5Convert psd to html5
Convert psd to html5Kim Hyun Hai
 
Trần Anh Khoa - Kautilya và Powershell trong kỹ thuật tấn công tiếp cận
Trần Anh Khoa - Kautilya và Powershelltrong kỹ thuật tấn công tiếp cậnTrần Anh Khoa - Kautilya và Powershelltrong kỹ thuật tấn công tiếp cận
Trần Anh Khoa - Kautilya và Powershell trong kỹ thuật tấn công tiếp cậnSecurity Bootcamp
 
Lập trình web - HTML cơ bản
Lập trình web - HTML cơ bảnLập trình web - HTML cơ bản
Lập trình web - HTML cơ bảnNhóc Nhóc
 

Similar to Chapter 3 - Introduction to Javascript (1).pdf (20)

Php cơ bản của trung tâm hocweb.com.vn
Php cơ bản của trung tâm hocweb.com.vnPhp cơ bản của trung tâm hocweb.com.vn
Php cơ bản của trung tâm hocweb.com.vn
 
Asp.net mvc 3 (c#) (9 tutorials) egroups vn
Asp.net mvc 3 (c#) (9 tutorials)   egroups vnAsp.net mvc 3 (c#) (9 tutorials)   egroups vn
Asp.net mvc 3 (c#) (9 tutorials) egroups vn
 
Ebook học Javascript cơ bản tới nâng cao
Ebook học Javascript cơ bản tới nâng caoEbook học Javascript cơ bản tới nâng cao
Ebook học Javascript cơ bản tới nâng cao
 
Java script dh bk share-book.com
Java script dh bk   share-book.comJava script dh bk   share-book.com
Java script dh bk share-book.com
 
Cq lt hdt-th2011-02-tuan04
Cq lt hdt-th2011-02-tuan04Cq lt hdt-th2011-02-tuan04
Cq lt hdt-th2011-02-tuan04
 
Giao trinh java_script (1)
Giao trinh java_script (1)Giao trinh java_script (1)
Giao trinh java_script (1)
 
Session 08 Final
Session 08 FinalSession 08 Final
Session 08 Final
 
JavaScript (Tieng viet)
JavaScript (Tieng viet)JavaScript (Tieng viet)
JavaScript (Tieng viet)
 
Giao trinh java_script
Giao trinh java_scriptGiao trinh java_script
Giao trinh java_script
 
Bài 4: JSP Cơ Bản - Lập Trình Mạng Nâng Cao
Bài 4: JSP Cơ Bản - Lập Trình Mạng Nâng CaoBài 4: JSP Cơ Bản - Lập Trình Mạng Nâng Cao
Bài 4: JSP Cơ Bản - Lập Trình Mạng Nâng Cao
 
00 webcourse -_introduction
00 webcourse -_introduction00 webcourse -_introduction
00 webcourse -_introduction
 
Convert psd to html5
Convert psd to html5Convert psd to html5
Convert psd to html5
 
Convert psd to html5 nhất nghệ - hoclaptrinhweb.com
Convert psd to html5 nhất nghệ - hoclaptrinhweb.comConvert psd to html5 nhất nghệ - hoclaptrinhweb.com
Convert psd to html5 nhất nghệ - hoclaptrinhweb.com
 
Tự học JavaScript
Tự học JavaScriptTự học JavaScript
Tự học JavaScript
 
Tu hoc javascript
Tu hoc javascriptTu hoc javascript
Tu hoc javascript
 
Convert psd to html5
Convert psd to html5Convert psd to html5
Convert psd to html5
 
Convert psd to html5
Convert psd to html5Convert psd to html5
Convert psd to html5
 
Ajax
AjaxAjax
Ajax
 
Trần Anh Khoa - Kautilya và Powershell trong kỹ thuật tấn công tiếp cận
Trần Anh Khoa - Kautilya và Powershelltrong kỹ thuật tấn công tiếp cậnTrần Anh Khoa - Kautilya và Powershelltrong kỹ thuật tấn công tiếp cận
Trần Anh Khoa - Kautilya và Powershell trong kỹ thuật tấn công tiếp cận
 
Lập trình web - HTML cơ bản
Lập trình web - HTML cơ bảnLập trình web - HTML cơ bản
Lập trình web - HTML cơ bản
 

Chapter 3 - Introduction to Javascript (1).pdf

  • 1. Chapter 3 Introduction to Javascript Lectured by: Nguyễn Hữu Hiếu
  • 2. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 2 JavaScript n JavaScript is the programming language of HTML and the Web. n Programming makes computers do what you want them to do. JavaScript is easy to learn. n This tutorial will teach you JavaScript from basic to advanced.
  • 3. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 3 Why Study JavaScript? n JavaScript is one of the 3 languages all web developers must learn: 1. HTML to define the content of web pages 2. CSS to specify the layout of web pages 3. JavaScript to program the behaviour of web pages n This lecture is about JavaScript, and how JavaScript works with HTML and CSS.
  • 4. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 4 JavaScript Introduction n JavaScript Can Change HTML Content One of many HTML methods is getElementById(). n This example uses the method to "find" an HTML element (with id="demo"), and changes the element content (innerHTML) to "Hello JavaScript”: document.getElementById("demo").innerHTML = "Hello JavaScript”;
  • 5. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 5 Example <!DOCTYPE html> <html> <body> <h1>What Can JavaScript Do?</h1> <p id="demo">JavaScript can change HTML content.</p> <button type="button" onclick="document.getElementById('demo').innerHTML = 'Hello JavaScript!'"> Click Me! </button> </body> </html>
  • 6. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 6 JavaScript Can Change HTML Attributes This example changes an HTML image, by changing the src attribute of an <img> tag: <!DOCTYPE html><html> <body> <h1>JavaScript Can Change Images</h1> <img id="myImage" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180”> <p>Click the light bulb to turn on/off the light.</p> <script> function changeImage() { var image = document.getElementById('myImage'); if (image.src.match("bulbon")) { image.src = "pic_bulboff.gif"; } else { image.src = "pic_bulbon.gif"; } } </script> </body> </html>
  • 7. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 7 JavaScript Can Change HTML Styles (CSS) <!DOCTYPE html> <html> <body> <h1>What Can JavaScript Do?</h1> <p id="demo">JavaScript can change the style of an HTML element.</p> <script> function myFunction() { var x = document.getElementById("demo"); x.style.fontSize = "25px"; x.style.color = "red"; } </script> <button type="button" onclick="myFunction()">Click Me!</button> </body> </html>
  • 8. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 8 JavaScript Can Validate Data n JavaScript is often used to validate input
  • 9. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 9 Did You Know? n JavaScript and Java are completely different languages, both in concept and design. n JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997. n ECMA-262 is the official name. ECMAScript 5 (JavaScript 1.8.5 - July 2010) is the current standard
  • 10. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 10 JavaScript Where To n JavaScript can be placed in the <body> and the <head> sections of an HTML page. n The <script> Tag In HTML, JavaScript code must be inserted between <script> and </script> tag <script> document.getElementById("demo").innerHTML = "My First JavaScript”; </script>
  • 11. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 11 JavaScript Functions and Events n A JavaScript function is a block of JavaScript code, that can be executed when "asked" for. n For example, a function can be executed when an event occurs, like when the user clicks a button. n You will learn much more about functions and events in later chapters.
  • 12. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 12 JavaScript in <head> or <body> n You can place any number of scripts in an HTML document. n Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both. n Keeping all code in one place, is always a good habit.
  • 13. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 13 JavaScript in <head> n In this example, a JavaScript function is placed in the <head> section of an HTML page. n The function is invoked (called) when a button is clicked:
  • 14. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 14 Example <!DOCTYPE html> <html> <head> <script> function myFunction() { document.getElementById("demo").innerHTML = "Paragraph changed."; } </script> </head> <body> <h1>My Web Page</h1> <p id="demo">A Paragraph</p> <button type="button" onclick="myFunction()">Try it</button> </body> </html>
  • 15. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 15 JavaScript in <body> n In this example, a JavaScript function is placed in the <body> section of an HTML page. n The function is invoked (called) when a button is clicked:
  • 16. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 16 Example <!DOCTYPE html> <html> <body> <h1>My Web Page</h1> <p id="demo">A Paragraph</p> <button type="button" onclick="myFunction()">Try it</button> <script> function myFunction() { document.getElementById("demo").innerHTML = "Paragraph changed."; } </script> </body> </html>
  • 17. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 17 External JavaScript n Scripts can also be placed in external files. n External scripts are practical when the same code is used in many different web pages. n JavaScript files have the file extension .js. To use an external script, put the name of the script file in the src (source) n attribute of the <script> tag: <!DOCTYPE html> <html> <body> <script src="myScript.js"></script> </body> </html>
  • 18. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 18 External JavaScript n You can place an external script reference in <head> or <body> as you like. n The script will behave as if it was located exactly where the <script> tag is located. n External scripts cannot contain <script> tags.
  • 19. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 19 External JavaScript Advantages n Placing JavaScripts in external files has some advantages: n It separates HTML and code n It makes HTML and JavaScript easier to read and maintain n Cached JavaScript files can speed up page loads
  • 20. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 20 JavaScript Output n JavaScript does not have any built-in print or display functions. n JavaScript Display Possibilities JavaScript can "display" data in different ways: 1. Writing into an alert box, using window.alert(). 2. Writing into the HTML output using document.write(). 3. Writing into an HTML element, using innerHTML. 4. Writing into the browser console, using console.log().
  • 21. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 21 Using window.alert() You can use an alert box to display: <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> window.alert(5 + 6); </script> </body> </html>
  • 22. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 22 Using document.write() For testing purposes, it is convenient to use document.write(): <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> document.write(5 + 6); </script> </body> </html>
  • 23. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 23 Using document.write() Using document.write() after an HTML document is fully loaded, will delete all existing HTML: <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <button onclick="document.write(5 + 6)">Try it</button> </body> </html>
  • 24. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 24 Using innerHTML n To access an HTML element, JavaScript can use the document.getElementById(id) method. n The id attribute defines the HTML element. The innerHTML property defines the HTML content:
  • 25. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 25 Example <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My First Paragraph</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 5 + 6; </script> </body> </html>
  • 26. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 26 Using console.log() n In your browser, you can use the console.log() method to display data. n Activate the browser console with F12, and select "Console" in the menu.
  • 27. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 27 Example <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> console.log(5 + 6); </script> </body> </html>
  • 28. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 28 JavaScript Syntax n JavaScript syntax is the set of rules, how JavaScript programs are constructed. n A computer program is a list of "instructions" to be "executed" by the computer. n In a programming language, these program instructions are called statements. n JavaScript is a programming language. JavaScript statements are separated by semicolon.
  • 29. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 29 Example <!DOCTYPE html> <html> <body> <h1>JavaScript Statements</h1> <p>Statements are separated by semicolons.</p> <p>The variables x, y, and z are assigned the values 5, 6, and 11:</p> <p id="demo"></p> <script> var x = 5; var y = 6; var z = x + y; document.getElementById("demo").innerHTML = z; </script> </body> </html>
  • 30. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 30 JavaScript Statements n JavaScript statements are composed of: n Values. n Operators. n Expressions. n Keywords. n Comments.
  • 31. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 31 1-JavaScript Values n The JavaScript syntax defines two types of values: Fixed values and variable values. n 1.1-Fixed values are called literals. n 2.1-Variable values are called variables.
  • 32. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 32 1.1-JavaScript Literals n The most important rules for writing fixed values are: n Numbers are written with or without decimals: n 10.50 n 1001 n Strings are text, written within double or single quotes: n "John Doe” n 'John Doe’ n Expressions can also represent fixed values: n 5+6 n 5 * 10
  • 33. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 33 1.2-JavaScript Variables n In a programming language, variables are used to store data values. n JavaScript uses the var keyword to define variables. An equal sign is used to assign values to variables. n In this example, x is defined as a variable. Then, x is assigned (given) the value 6: n var x; n x = 6;
  • 34. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 34 2-JavaScript Operators n JavaScript uses an assignment operator ( = ) to assign values to variables: n var x = 5; n var y = 6; n JavaScript uses arithmetic operators ( + - * / ) to compute values: (5 + 6) * 10
  • 35. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 35 Object literals 35 n You don’t declare the types of variables in JavaScript n JavaScript has object literals, written with this syntax: n { name1 : value1 , ... , nameN : valueN } n Example (from Netscape’s documentation): n car = {myCar: "Saturn", 7: "Mazda", getCar: CarTypes("Honda"), special: Sales} n The fields are myCar, getCar, 7 (this is a legal field name) , and special n "Saturn" and "Mazda" are Strings n CarTypes is a function call n Sales is a variable you defined earlier n Example use: document.write("I own a " + car.myCar);
  • 36. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 36 Three ways to create an object 36 n You can use an object literal: n var course = { number: "CIT597", teacher: "Dr. Dave" } n You can use new to create a “blank” object, and add fields to it later: n var course = new Object(); course.number = "CIT597"; course.teacher = "Dr. Dave"; n You can write and use a constructor: n function Course(n, t) { // best placed in <head> this.number = n; // keyword "this" is required, not optional this.teacher = t; } n var course = new Course("CIT597", "Dr. Dave");
  • 37. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 37 Array literals 37 n You don’t declare the types of variables in JavaScript n JavaScript has array literals, written with brackets and commas n Example: color = ["red", "yellow", "green", "blue"]; n Arrays are zero-based: color[0] is "red" n If you put two commas in a row, the array has an “empty” element in that location n Example: color = ["red", , , "green", "blue"]; n color has 5 elements n However, a single comma at the end is ignored n Example: color = ["red", , , "green", "blue”,]; still has 5 elements
  • 38. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 38 Four ways to create an array 38 n You can use an array literal: var colors = ["red", "green", "blue"]; n You can use new Array() to create an empty array: n var colors = new Array(); n You can add elements to the array later: colors[0] = "red"; colors[2] = "blue"; colors[1]="green"; n You can use new Array(n) with a single numeric argument to create an array of that size n var colors = new Array(3); n You can use new Array(…) with two or more arguments to create an array containing those values: n var colors = new Array("red","green", "blue");
  • 39. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 39 The length of an array 39 n If myArray is an array, its length is given by myArray.length n Array length can be changed by assignment beyond the current length n Example: var myArray = new Array(5); myArray[10] = 3; n Arrays are sparse, that is, space is only allocated for elements that have been assigned a value n Example: myArray[50000] = 3; is perfectly OK n But indices must be between 0 and 232-1 n As in C and Java, there are no two-dimensional arrays; but you can have an array of arrays: myArray[5][3]
  • 40. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 40 Arrays and objects 40 n Arrays are objects n car = { myCar: "Saturn", 7: "Mazda" } n car[7] is the same as car.7 n car.myCar is the same as car["myCar"] n If you know the name of a property, you can use dot notation: car.myCar n If you don’t know the name of a property, but you have it in a variable (or can compute it), you must use array notation: car["my" + "Car"]
  • 41. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 41 Array functions 41 n If myArray is an array, n myArray.sort() sorts the array alphabetically n myArray.sort(function(a, b) { return a - b; }) sorts numerically n myArray.reverse() reverses the array elements n myArray.push(…) adds any number of new elements to the end of the array, and increases the array’s length n myArray.pop() removes and returns the last element of the array, and decrements the array’s length n myArray.toString() returns a string containing the values of the array elements, separated by commas
  • 42. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 42 The for…in statement 42 n You can loop through all the properties of an object with for (variable in object) statement; n Example: for (var prop in course) { document.write(prop + ": " + course[prop]); } n Possible output: teacher: Dr. Dave number: CIT597 n The properties are accessed in an undefined order n If you add or delete properties of the object within the loop, it is undefined whether the loop will visit those properties n Arrays are objects; applied to an array, for…in will visit the “properties” 0, 1, 2, … n Notice that course["teacher"] is equivalent to course.teacher n You must use brackets if the property name is in a variable
  • 43. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 43 3-JavaScript Keywords n JavaScript keywords are used to identify actions to be performed. n The var keyword tells the browser to create a new variable: n var x = 5 + 6; n var y = x * 10;
  • 44. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 44 4-JavaScript Comments n Not all JavaScript statements are "executed". n Code after double slashes // or between /* and */ is n treated as a comment. n Comments are ignored, and will not be executed: var x = 5; // I will be executed // var x = 6; I will NOT be executed
  • 45. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 45 JavaScript is Case Sensitive n All JavaScript identifiers are case sensitive. The variables lastName and lastname, are two different variables. lastName = "Doe”; lastname = “Peterson";
  • 46. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 46 JavaScript and Camel Case n Historically, programmers have used three ways of joining multiple words into one variable name: n Hyphens: n first-name, last-name, master-card, inter-city. n Underscore: n first_name, last_name, master_card, inter_city. n Camel Case: n FirstName, LastName, MasterCard, InterCity. n Hyphens are not allowed in JavaScript. It is reserved for subtractions.
  • 47. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 47 JavaScript Statements n In HTML, JavaScript statements are "instructions" to be "executed" by the web browser. n This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo": n Example: document.getElementById("demo").innerHTML = "Hello Dolly.”;
  • 48. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 48 JavaScript Programs n Most JavaScript programs contain many JavaScript statements. n The statements are executed, one by one, in the same order as they are written. n In this example, x, y, and z is given values, and finally z is displayed: Example: var x = 5; var y = 6; var z = x + y; document.getElementById("demo").innerHTML = z; n JavaScript programs (and JavaScript statements) are often called JavaScript code.
  • 49. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 49 Semicolons ; n Semicolons separate JavaScript statements. n Add a semicolon at the end of each executable statement: a = 5; b = 6; c = a + b; When separated by semicolons, multiple statements on one line are allowed: a = 5; b = 6; c = a + b; n On the web, you might see examples without semicolons. Ending statements with semicolon is not required, but highly recommended.
  • 50. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 50 JavaScript White Space n JavaScript ignores multiple spaces. You can add white space to your script to make it more readable. n The following lines are equivalent: var person = "Hege"; var person=“Hege”; n A good practice is to put spaces around operators ( = + - * / ): var x = y + z;
  • 51. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 51 JavaScript Line Length and Line Breaks n For best readability, programmers often like to avoid code lines longer than 80 characters. If a JavaScript statement does not fit on one line, the best place to break it, is after an operator: document.getElementById("demo").innerHTML = "Hello Dolly.”;
  • 52. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 52 JavaScript Code Blocks n JavaScript statements can be grouped together in code blocks, inside curly brackets {...}. n The purpose of code blocks this is to define statements to be executed together. n One place you will find statements grouped together in blocks, are in JavaScript functions: function myFunction() { document.getElementById("demo").innerHTML = "Hello Dolly."; document.getElementById("myDIV").innerHTML = "How are you?"; }
  • 53. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 53 JavaScript Keywords n JavaScript statements often start with a keyword to identify the JavaScript action to be performed. n Here is a list of some of the keywords you will learn about in this lecture: n JavaScript keywords are reserved words. Reserved words cannot be used as names for variables.
  • 54. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 54 JavaScript Keywords
  • 55. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 55 Value = undefined n In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input. n A variable declared without a value will have the value undefined. The variable carName will have the value undefined after the execution of this statement: n Example var carName;
  • 56. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 56 Control Structures n There are three basic types of control structures in JavaScript: the if statement, the while loop, and the for loop n Each control structure manipulates a block of JavaScript expressions beginning with { and ending with }
  • 57. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 57 The If Statement If ( x = = 10) { y = x*x; } else { x = 0; } n The if statement allows JavaScript programmers to a make decision n Use an if statement whenever you come to a “fork” in the program
  • 58. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 58 Repeat Loops n A repeat loop is a group of statements that is repeated until a specified condition is met n Repeat loops are very powerful programming tools; They allow for more efficient program design and are ideally suited for working with arrays
  • 59. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 59 The While Loop count = 0; while (count <= 10) { document.write(count); count++; } n The while loop is used to execute a block of code while a certain condition is true
  • 60. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 60 The For Loop n The for loop is used when there is a need to have a counter of some kind n The counter is initialized before the loop starts, tested after each iteration to see if it is below a target value, and finally updated at the end of the loop
  • 61. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 61 Example: For Loop i=1 initializes the counter i<=10 is the target value i++ updates the counter at the end of the loop // Print the numbers 1 through 10 for (i=1; i<= 10; i++) document.write(i);
  • 62. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 62 Example: For Loop <SCRIPT> for (i=1; i<=5; i++) { document.write(i); } </SCRIPT> <SCRIPT> document.write("1"); document.write("2"); document.write("3"); document.write("4"); document.write("5"); </SCRIPT>
  • 63. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 63 Functions n Functions are a collection of JavaScript statement that performs a specified task n Functions are used whenever it is necessary to repeat an operation
  • 64. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 64 Functions n Functions have inputs and outputs n The inputs are passed into the function and are known as arguments or parameters n Think of a function as a “black box” which performs an operation
  • 65. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 65 Defining Functions n The most common way to define a function is with the function statement. n The function statement consists of the function keyword followed by the name of the function, a comma-separated list of parameter names in parentheses, and the statements which contain the body of the function enclosed in curly braces
  • 66. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 66 Example: Function Name of Function: square Input/Argument: x Output: x*x function square(x) { return x*x; } z = 3; sqr_z = square(z);
  • 67. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 67 Example: Function function sum_of_squares(num1,num2) { return (num1*num1) + (num2*num2); } function sum_of_squares(num1,num2) { return (square(num1) + square(num2)); }
  • 68. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 68 Javscript Events 68 n Events are actions that can be detected by Javascript n Every element on a web page has certain events which can trigger Javascript functions n Often placed within the HTML tag n <tag attribute1 attribute2 onEventName="javascript code;"> n <a href="" onMouseOver="popupFunc();"> n The set of all events which may occur and the page elements on which they can occur is part of the Document Object Model(DOM) not Javascript n Browsers don’t necessarily share the same set of events
  • 69. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 69 Common Javascript Events 69 Event Occurs when... Event Handler n click User clicks on form element or link onClick n change User changes value of text, textarea, or select element onChange n focus User gives form element input focus onFocus n blur User removes input focus from form element onBlur n mouseover User moves mouse pointer over a link or anchor onMouseOver n mouseout User moves mouse pointer off of link or anchor onMouseOut n select User selects form element's input field onSelect n submit User submits a form onSubmit n resize User resizes the browser window onResize n load User loads the page in the Navigator onLoad n unload User exits the page onUnload
  • 70. 5.2 DOM (Document Object Model)
  • 71. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 71 The Document Object Model 71 n When a document is loaded in the web browser, a number of objects are created. n Most commonly used are window and document n Window n open(), close(), alert(), confirm(), prompt() n Document n Contains arrays which store all the components of your page n You can access and call methods on the components using the arrays n An object may also be accessed by its name n document.myform.address.value = “123 Main” n document.myform.reset() n Can also search for element by name or id n document.getElementById(“myelementid”) n document.getElementsByName(“myelementname”)
  • 72. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 72 DOM & DHTML n Dynamic web pages with JavaScript and DOM n DHTML (Dynamic HTML) n DOM nodes and DOM tree n Traversing, editing and modifying DOM nodes n Editing text nodes n Accessing, editing and modifying elements' attributes
  • 73. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 73 DOM Concept n DOM makes all components of a web page accessible n HTML elements n their attributes n text n They can be created, modified and removed with JavaScript
  • 74. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 74 DOM Objects n DOM components are accessible as objects or collections of objects n DOM components form a tree of nodes • relationship parent node – children nodes • document is the root node n Attributes of elements are accessible as text n Browsers can show DOM visually as an expandable tree n Firebug for Firefox n in IE -> Tools -> Developer Tools
  • 75. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 75 DOM Standards n W3C www.w3.org defines the standards n DOM Level 3 recommendation n www.w3.org/TR/DOM-Level-3-Core/ n DOM Level 2 HTML Specification n www.w3.org/TR/DOM-Level-2-HTML/ n additional DOM functionality specific to HTML, in particular objects for XHTML elements n But, the developers of web browsers n don't implement all standards n implement some standards differently n implement some additional features
  • 76. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 76 Accessing Nodes by id n Access to elements by their id n document.getElementById(<id>) n returns the element with id <id> n id attribute can be defined in each start tag n div element with id attribute can be used as an root node for a dynamic DOM subtree n span element with id attribute can be used as a dynamic inline element n The preferred way to access elements
  • 77. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 77 Other Access Methods n Access by elements' tag n there are typically several elements with the same tag n document.getElementsByTagName(<tag>) n returns the collection of all elements whose tag is <tag> n the collection has a length attribute n an item in the collection can be reached by its index n e.g. n var html = document.getElementsByTagName("html")[0]; n Access by elements' name attribute n several elements can have the same name n document.getElementsByName(<name>) n returns the collection of elements with name <name>
  • 78. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 78 Traversing DOM tree n Traversal through node properties n childNodes property n the value is a collection of nodes n has a length attribute n an item can be reached by its index n e.g. var body = html.childNodes[1]; n firstChild, lastChild properties n nextSibling, previousSibling properties n parentNode property
  • 79. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 79 Other Node Properties • nodeType property n ELEMENT_NODE: HTML element n TEXT_NODE: text within a parent element n ATTRIBUTE_NODE: an attribute of a parent element n attributes can be accessed another way n CDATA_SECTION_NODE n CDATA sections are good for unformatted text n nodeName property n nodeValue property n attributes property n innerHTML property n not standard, but implemented in major browsers n very useful n style property n object whose properties are all style attributes, e.g., those defied in CSS
  • 80. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 80 Accessing JS Object's Properties n There are two different syntax forms to access object's properties in JS ( n <object>.<property> n dot notation, e.g., document.nodeType n <object>[<property-name> ] n brackets notation, e.g., document["nodeType"] n this is used in for-in loops n this works for properties of DOM objects, too
  • 81. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 81 Attributes of Elements • Access through attributes property n attributes is an array n has a length attribute n an item can be reached by its index n an item has the properties name and value n e.g. n var src = document.images[0].attributes[0].value; n Access through function getAttribute(<name>) n returns the value of attribute <name> n e.g. n var src = document.images[0].getAttribute("src");
  • 82. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 82 Text Nodes n Text node n can only be as a leaf in DOM tree n it’s nodeValue property holds the text n innerHTML can be used to access the text n Watch out: n There are many more text nodes than you would expect!
  • 83. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 83 Modifying DOM Structure n document.createElement(<tag>) n creates a new DOM element node, with <tag> tag. n the node still needs to be inserted into the DOM tree n document.createTextNode(<text>) n creates a new DOM text with <text> n the node still needs to be inserted into the DOM tree n <parent>.appendChild(<child>) n inserts <child> node behind all existing children of <parent> node n <parent>.insertBefore(<child>,<before>) n inserts <child> node before <before> child within <parent> node n <parent>.replaceChild(<child>,<instead>) n replaces <instead> child by <child> node within <parent> node n <parent>.removeChild(<child>) n removes <child> node from within <parent> node
  • 84. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 84 Modifying Node Attributes n <node>.setAttribute(<name>,<value>) n sets the value of attribute <name> to <value> n e.g. n document.images[0].setAttribute("src","keiki.jpg"); n That's the standard n but it doesn't work in IE, there you have to use n setAttribute(<name=value>) n e.g. n document.images[0].setAttribute("src="keiki.jpg"");
  • 85. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 85 W3C Document Object Model
  • 86. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 86 Special DOM Objects n window n the browser window n new popup windows can be opened n document n the current web page inside the window n body n <body> element of the document n history n sites that the user visited n makes it possible to go back and forth using scripts n location n URL of the document n setting it goes to another page
  • 87. Trường Đại Học Bách Khoa TP.HCM Khoa Khoa Học và Kỹ Thuật Máy Tính © 2017 Lập Trình Web 87 Tài Liệu Tham Khảo n [1] Stepp,Miller,Kirst. Web Programming Step by Step.( 1st Edition, 2009) Companion Website: http://www.webstepbook.com/ n [2] W3Schools, http://www.w3schools.com/html/default.asp