Trường Đại Học Bách Khoa TP.HCMKhoa 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.. Trường Đại Học Bách K
Trang 1Chapter 3 Introduction to Javascript
Lectured by:
Nguyễn Hữu Hiếu
Trang 2Trườ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
them to do JavaScript is easy to learn
n This tutorial will teach you JavaScript from basic to advanced
Trang 3Why 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
Trang 4Trườ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”;
Trang 5<!DOCTYPE html>
<html>
<body>
<h1>What Can JavaScript Do?</h1>
<p id="demo">JavaScript can change HTML content.</p>
Trang 6Trườ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"
Trang 7JavaScript 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>
Trang 8Trườ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
Trang 9Did 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
Trang 10Trườ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>
Trang 11JavaScript 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
Trang 12Trườ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
Trang 13JavaScript 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:
Trang 14Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
Trang 15JavaScript 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:
Trang 16Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
</script>
</body>
</html>
Trang 17External JavaScript
many different web pages
To use an external script, put the name of the script file in the src (source)
n attribute of the <script> tag:
Trang 18Trườ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
<body> as you like
<script> tag is located
Trang 19External JavaScript Advantages
n Placing JavaScripts in external files has some
advantages:
maintain
Trang 20Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
Trang 21<h1>My First Web Page</h1>
<p>My first paragraph.</p>
Trang 22Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
Trang 23Using 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>
Trang 24Trườ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:
Trang 25<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
Trang 26Trườ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
Trang 27<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
Trang 28Trườ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
Trang 29<p>Statements are separated by semicolons.</p>
<p>The variables x, y, and z are assigned the values 5, 6, and 11:</p>
Trang 30Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
Trang 311-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
Trang 32Trườ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 Numbers are written with or without decimals:
Trang 33An 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:
Trang 34Trườ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 JavaScript uses arithmetic operators ( + - * / ) to
compute values: (5 + 6) * 10
Trang 35Object literals
n { name1 : value1 , , nameN : valueN }
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);
Trang 36Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
n var course = { number: "CIT597", teacher: "Dr Dave" }
to it later:
n var course = new Object();
course.number = "CIT597";
course.teacher = "Dr Dave";
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");
Trang 37Array literals
commas
n Example: color = ["red", "yellow", "green", "blue"];
n Arrays are zero-based: color[0] is "red"
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
Trang 38Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
var colors = ["red", "green", "blue"];
n var colors = new Array();
n You can add elements to the array later:
colors[0] = "red"; colors[2] = "blue"; colors[1]="green";
argument to create an array of that size
n var colors = new Array(3);
arguments to create an array containing those
values:
n var colors = new Array("red","green", "blue");
Trang 39The length of an array
n If myArray is an array, its length is given by
myArray.length
the current length
n Example: var myArray = new Array(5); myArray[10] = 3;
elements that have been assigned a value
n Example: myArray[50000] = 3; is perfectly OK
n But indices must be between 0 and 2 32 -1
Trang 40Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
n car = { myCar: "Saturn", 7: "Mazda" }
n car[7] is the same as car.7
n car.myCar is the same as car["myCar"]
notation: car["my" + "Car"]
Trang 41Array functions
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
Trang 42Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
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
Trang 44Trườ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
var x = 5; // I will be executed
// var x = 6; I will NOT be executed
Trang 45JavaScript is Case Sensitive
The variables lastName and lastname, are two different
variables
lastName = "Doe”;
lastname = “Peterson";
Trang 46Trườ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
multiple words into one variable name:
n FirstName, LastName, MasterCard, InterCity
subtractions
Trang 47JavaScript Statements
"executed" by the web browser
inside an HTML element with id="demo":
document.getElementById("demo").innerHTML = "Hello Dolly.”;
Trang 48Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
order as they are written
called JavaScript code
Trang 49Semicolons ;
Ending statements with semicolon is not required, but
highly recommended
Trang 50Trườ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
space to your script to make it more readable
var person=“Hege”;
/ ):
var x = y + z;
Trang 51JavaScript Line Length and Line Breaks
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.”;
Trang 52Trườ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
blocks, inside curly brackets { }
be executed together
blocks, are in JavaScript functions:
function myFunction() {
document.getElementById("demo").innerHTML = "Hello Dolly.";
document.getElementById("myDIV").innerHTML = "How are you?";
}
Trang 53JavaScript Keywords
the JavaScript action to be performed
in this lecture:
cannot be used as names for variables
Trang 54Trườ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
Trang 55Value = undefined
a value The value can be something that has to be
calculated, or something that will be provided later, like
user input
undefined The variable carName will have the value
undefined after the execution of this statement:
var carName;
Trang 56Trườ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
JavaScript: the if statement, the while loop, and the
for loop
expressions beginning with { and ending with }
Trang 57The If Statement
If ( x = = 10)
} else
Trang 58Trườ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
a specified condition is met
allow for more efficient program design and are ideally
suited for working with arrays
Trang 59The While Loop
count = 0;
while (count <= 10) { document.write(count); count++;
Trang 60Trườ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
counter of some kind
each iteration to see if it is below a target value, and finally updated at the end of the loop
Trang 61Example: For Loop
i=1 initializes the counter
i<=10 is the target
value
i++ updates the
counter at the end
Trang 62Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
Trang 63performs a specified task
operation
Trang 64Trườ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
arguments or parameters
operation
Trang 65Defining Functions
function statement
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
Trang 66Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
Trang 68Trường Đại Học Bách Khoa TP.HCM
Khoa Khoa Học và Kỹ Thuật Máy Tính
trigger Javascript functions
n <tag attribute1 attribute2 onEventName="javascript code;">
n <a href="" onMouseOver="popupFunc();">
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
Trang 69Common Javascript Events
n change User changes value of text, textarea, or select element onChange
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