Ch3 - JavaScript
Ch3 - JavaScript
Chapter 3
JavaScript
2019
Tran Cong An
(tcan@cit.ctu.edu.vn)
Content
1. Introduction
2. Using JavaScript in an HTML documents
3. JS language basics
4. JS functions
5. DOM
6. OOP in JS
7. Appendix
2
Introduction to JavaScript
3
Introduction to JS
What is JavaScript?
4
Introduction to JS
Why JavaScript?
+ produces
6
Introduction to JS
Basic Features of JS
7
Using JS in HTML Documents
8
Using JS in HTML Documents
Internal JS Code
vNote: Placing scripts at the bottom of the <body> element improves the
display speed, because script compilation slows down the display
9
Using JS in HTML Documents
External JS Code
Recommended!
10
Using JS in HTML Documents
External JS Code
- Example:
<script src="scripts/myscript1.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
vNotes:
• External JS scripts cannot contain <script> tags
• The <script> tag can be placed anywhere in the HTML page
• An HTML page can use multiple script files: use multiple <script>
tags to link to multiple script files
11
Using JS in HTML Documents
- JS script execution:
• There is no main function as other programming languages
⇒ The script code is executed from the top to the bottom
• JS functions in the script file are only executed when called
12
Using JS in HTML Documents
Output of JS
13
Using JS in HTML Documents
Output of JS
14
Using JS in HTML Documents
Output of JS
15
Using JS in HTML Documents
Output of JS
16
Using JS in HTML Documents
Output of JS
1. Right click
3. Choose Console
2. Click Inspect
17
JS Language Basics
18
JS Language Basics
Statements
19
JS Language Basics
Comments
20
JS Language Basics
Variables
21
JS Language Basics
Variables
22
JS Language Basics
Operators
Assignment
Arithmetic
23
JS Language Basics
Operators
Logical
String
Datatypes
25
JS Language Basics
Numbers
26
JS Language Basics
Strings
- Object type
- Can be defined with single quote (preferred) or double quote
- Immutable
- No char type: letters are strings with length 1
- Methods: charAt, charCodeAt, fromCharCode, indexOf,
lastIndexOf, replace, split, join, substring,
toLowerCase, toUpperCase
- Property: length
- The only operator: +
27
JS Language Basics
28
JS Language Basics
Boolean
29
JS Language Basics
Boolean
if (username) {
// username is defined
}
else {
//username is not defined
}
30
JS Language Basics
Equality
31
JS Language Basics
Equality
32
JS Language Basics
33
JS Language Basics
Arrays
34
JS Language Basics
Arrays
35
JS Language Basics
Arrays
36
JS Language Basics
37
JS Language Basics
- Syntax:
if (condition1) {
//block of code to be executed if condition1 is true
} else if (condition2) {
//block of code to be executed if the condition1 is false and condition2 is true
}
...
else {
//block of code to be executed if the condition1 is false and condition2 is false
}
38
JS Language Basics
39
JS Language Basics
- Syntax:
switch(expression) {
case x:
//code block to be executed when expression = x
break;
case y:
// code block to be executed when expression = y
break;
...
default:
// code block to be executed when all above cases
}
40
JS Language Basics
41
JS Language Basics
Loop – for
- Syntax:
for (statement 1; statement 2; statement 3) {
//code block to be executed
}
- Example:
for (var i = 1; i <= 6; i++) {
document.write("<h" + i + ">");
document.write("Heading " + i);
document.write("</h" + i + ">");
}
42
JS Language Basics
- Syntax:
while (condition) {
// code block to be executed
}
do {
//code block to be executed
} while (condition);
43
JS Language Basics
break statement
44
JS Language Basics
continue statement
45
JS Functions
46
JS Functions
Function Declaration
- Syntax:
function func_name(parameters) {
//function body (statements)
}
function hello(name) {
console.log("Hello " + name);
}
hello("Messi");
47
JS Functions
Function Expression
48
JS Functions
Function Expression
49
JS Functions
Function Parameters
50
JS Functions
Function Parameters
function findMax() {
var i;
var max = -Infinity;
for (i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
51
JS Functions
52
Document Object Model (DOM)
55
Document Object Model (DOM)
57
Document Object Model (DOM)
58
Document Object Model (DOM)
59
Document Object Model (DOM)
60
Document Object Model (DOM)
61
Document Object Model (DOM)
63
Document Object Model (DOM)
- nodeName:
• Element node: tag name (e.g. “P”, “IMG”, etc.)
• Attribute node: attribute name (e.g. “src”, ”href”, etc.)
• Text/Document node: “#text”, “#document”
- nodeValue:
• Element node: “undefine”
• Text node: text value of the node
• Attribute node: value of the attribute
- Note: to access a property value, using the syntax
<node>.<attribute_name>
64
Document Object Model (DOM)
<html>
<body>
<p id="par1">Hello World</p>
<p><img id="img1" src="flowers.jpeg"/>
<img id="img2" src="flowers.jpeg"/>
</p>
<script type="text/javascript">
var p1 = document.getElementById("par1");
p1.innerHTML = "New text";
var m2 = document.getElementById("img2");
m2.src = "birds.jpg";
</script>
</body>
</html>
65
Document Object Model (DOM)
<body>
<p id="par1">The first paragraph</p>
<p id="par2">The second paragraph</p>
<script type="text/javascript">
var p1 = document.getElementById("par1");
p1.style.fontSize = "x-large";
var p2 = document.getElementById("par2");
p2.style.color = "blue";
p2.style.border = "2px dotted #0000FF";
</script>
</body>
66
Document Object Model (DOM)
68
Events
HTML Events
69
Events
HTML Events
<html>
<head>
<script>
function displayDate(eid) {
var e = document.getElementById(eid);
e.innerText = Date();
}
</script>
</head>
<body>
<input type="button" value="Click me!" id="bt1"
onclick="displayDate('demo');"
onmouseover="this.style.color='red';" onmouseout="
this.style.color='black';"/>
<p id="demo">...</p>
</body>
</html>
70
Events
HTML Events
<script>
function prompttext(getf, inp) {
if (getf && (inp.value == "enter your name")) {
inp.value = "";
inp.style.color = "black";
}
if (!getf && (inp.value == "")) {
inp.value = "enter your name";
inp.style.color = "gray";
}
}
</script>
71
Events
- Each DOM object has the following method for event handling:
addEventListener(event name, function name);
• event name: the string of name of the event to listen to
• function name: the name of the JS function that will be executed
when the event fires (this function gets an Event object as param)
Pros: separate JS code from HTML markup
An event can be handled by multiple functions
- To stop listen to an event use the following function:
removeEventListener(event name, function name);
(the parameters are similar to the addEventListerner())
72
Events
function validate(event) {
alert("You click the object: " + event.target);
var x = document.getElementsByName("fname")[0].value;
if (x == "")
alert("Name must be filled out");
else
alert("Hello: " + x);
}
</script>
<body>
<p> Name <input type="text" name="fname">
<input id="myButton" type="button" value="Click me!">
</p>
</body>
73
OOP in JS
74
OOP in JS
JS Objects
75
OOP in JS
JS Objects
76
OOP in JS
Create a JS Object
77
OOP in JS
Create a JS Object
scores = {
peach: 100,
mario: 88,
luigi: 91
};
scores.toad = 72;
let name = 'wario';
scores[name] = 102;
console.log(scores);
79
OOP in JS
80
OOP in JS
- Use the for ... in loop (for each property in the object):
for (key in object) {
//do something with object[key]
}
- Example:
for (let name in scores) {
console.log(name + ' got ' + scores[name]);
}
81
OOP in JS
Prototype
82
OOP in JS
Prototype
83
OOP in JS
Prototype
Person.prototype.count = 0;
84
Appendix
85
Appendix
Alert Box
86
Appendix
Confirm Box
87
Appendix
Prompt Box
88
Appendix
Further Reading
89
Question?
Chapter 3 – JavaScript
90