Professional Documents
Culture Documents
KTLT 2-6
KTLT 2-6
KTLT 2-6
1
DOM (Document Object Model)
2
HTML DOM
method property
3
HTML DOM
Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(new, old) Replace an HTML element
document.write(text) Write into the HTML output stream
document.getElementById(id).onclick =
Adding event handler code to an onclick event
function(){code}
Property Description
element.innerHTML = new html content Change the inner HTML of an element
element.attribute = new value Change the attribute value of an HTML element
element.style.property = new style Change the style of an HTML element
https://www.w3schools.com 4
Using HTML DOM with JavaScript
<script>
const element = document.getElementById(“p1");
element.innerHTML = “Hi !";
</script>
5
Using HTML DOM with JavaScript
6
Using HTML DOM with JavaScript
• Validate input
<input id="number">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
let x = document.getElementById("number").value;
let text;
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>
8
Using HTML DOM with JavaScript
• Form Validation
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name can not be empty");
return false;
}
}
</script>
....
<form name="myForm" action="/action.php" onsubmit="return validateForm()"
method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
9
Using HTML DOM with JavaScript
10
Using HTML DOM with JavaScript
12
Other extensions
Browser Object Model
• Window Object
• window.open() - open a new window
• window.close() - close the current window
• window.moveTo() - move the current window
• window.resizeTo() - resize the current window
• window.screen
• window.location
• window.history
• window.navigator
• window.prompt(), window.confirm(), window.alert()
• Timing
• Cookies
14
Asynchronous JavaScript And XML
• AJAX
• Read data from a web server - after the page has loaded
• Update a web page without reloading the page
• Send data to a web server - in the background
• not a programming language
• a combination of:
• A browser built-in XMLHttpRequest object (to request data from a web server)
• JavaScript and HTML DOM (to display or use the data)
https://www.w3schools.com/js/js_ajax_intro.asp
15
JSON
16
JavaScript / jQuery DOM Selectors
17
Chapter 3: Variables and Data Types
1
Content
1. Variables
2. Basic data types
3. String
4. Array
5. Object
6. Other techniques
2
1. Variables
3
Variable concept
4
Variable concept
• Type:
• what can be stored in the box
Variable name
• normally unchanged after setting
• size of the box, type of the box
• Value:
• value of each bit in the box (0,1)
• corresponding to value of the variable
5
Working with variable
6
Working with variable in JavaScript
• Declaration a variable
let mes = ‘hello’;
In old scripts:
var message = 'Hi';
7
Working with variable in JavaScript
8
Working with variable in JavaScript
9
Identifier Concept
• Identifier :
• tokens that represent names of variables, constants, methods, objects,
classes, files
• unique in the program
10
Identifier Concept (2)
• Naming convention:
• Must be reminiscent
• For example, the identifier "bookPrice" rather than "bp" should be
used to store information about the price of a book
• Start with letters
• For Class: capitalize the first letter of each word
• TheExample
• For method/field: Start with a lowercase letter, capitalize the first letter
of the remaining words
• theExample
• For constants:
• value of the variable can’t be changed
• Naming in all capitalization
11
JavaScript Keywords
12
2. Basic data types in JavaScript
13
Data types in JavaScript
14
Number
15
Integer Number
Integer literals
• 10 Decimal
• Octal (0)
032 = 011 010(2) = 16 + 8 + 2 = 26(10)
• Hexadecimal (0x):
0x1A = 0001 1010(2) = 16 + 8 + 2 = 26(10)
• Binary (0b):
0b11111111 = 255 (10)
• Exponent (e):
5e2 500
5e-2 0.05
0.5e2 50
16
Number
• num.toString(); num.toString(base)
• returns a string representing the specified number value
• in the decimal or the given base numeral system
let num = 255;
num.toString(16) // ”FF”
num.toString(2) // ”11111111”
255..toString(16) // ”FF” -- Two dots
(255).toString(16) // ”FF” -- or parenthesis , etc.
parseInt('13.4') // 13
parseFloat('13.4.5') // 13.4
17
NaN - Number.NaN
• When NaN is one of the operands of any relational comparison (>, <, >=, <=), the
result is always false
• NaN compares unequal to any other value — including to another NaN value
18
NaN - Number.NaN
• isNaN(value)
• return true if the value is currently NaN, or after converting the value to a
number, the result is NaN
isNaN("hello world"); // true
isNaN("NaN"); // true
isNaN(true); // false (1)
isNaN("37"); // false (37)
isNaN(""); // false (0)
• Number.isNaN(value)
• return true only if the value is currently NaN
• non-numbers always return false
Number.isNaN("hello world"); // false
Number.isNaN(0 / 0); // true
Number.isNaN(NaN); // true
19
Infinity
console.log(Infinity ); /* Infinity */
console.log(Infinity + 1 ); /* Infinity */
console.log(Math.pow(10, 1000)); /* Infinity */
console.log(Math.log(0) ); /* -Infinity */
console.log(1 / Infinity ); /* 0 */
console.log(1 / 0 ); /* Infinity */
20
Infinity
• isFinite(value)
• converts value to a number (if needed)
• return true if the result is not NaN/Infinity/-Infinity/undefined
• Number.isFinite(value)
• checks whether value belongs to the number type, and not being
NaN/Infinity/-Infinity
• return true if the given value is a finite number.
21
BigInt
22
The “null” value
function hasVowels(str) {
const m = str.match(/[aeiou]/gi);
if (m === null) {
return 0;
}
return 1;
}
23
The “undefined” value
let mess;
alert(mess); // undefined
24
Boolean (logical type)
• What is false:
• false (boolean), 0 (number), -0 (number), 0n (BigInt), “” (empty string)
• null, undefined, NaN
25
Symbol
26
typeof operator
27
3. String in JavaScript
28
String
• Control keys
• \b backspace
• \f form feed
• \n newline
• \r return (go to beginning of line)
• \t tab
• Special characters in strings
• \" quotation mark
• \’ apostrophe
• \\ backslash
• \0: NUL character
• \xHH: specifies a character via an ASCII code
• \uHHHH: specifies a character via an UTF-16 code
29
Working with string
30
Working with string
31
4. Arrays in JavaScript
32
4. Arrays in JavaScript
33
Arrays
• In JavaScript:
• can add a new element to the array (extend the array)
let fruits = ["Apple", "Orange", "Pear"];
fruits[3] = 'Lemon'; // now ["Apple", "Orange", "Pear", "Lemon"]
34
Working with array
35
Working with array
36
Working with array
• Split
let names = ‘Peter, James, Mary’;
let arr = names.split(', ');
// arr = [‘Peter', ‘James', ‘Mary']
• and join
let arr = ['Peter', ‘James', ‘Mary'];
let str = arr.join(';'); // glue the array into a string using ;
// str will be ‘Peter;James;Mary’
• etc.
37
5. Objects in JavaScript
38
5. Objects in JavaScript
• Declaration:
39
Object
phrase "Hello!"
let user = {
name: "John"
};
user address of
// copy the reference true object
let admin = user; name: “John”
admin address of
the same object
40
Object
41
6. Other techniques
42
Type Conversions
• String conversion:
• need the string form of a value
• 3 + ‘times’ ‘3 times’
• String(value) function
• .toString() function
• Numeric Conversion:
• in mathematic operator:
• "6" / "2" = 3
• to convert explicitly: use Number(value) function
let num = Number(“364”); // becomes a number 364
alert(typeof num); // number
43
Type Conversions
44
Type Conversions
• Boolean Conversion
• Values like 0, empty string, null, undefined, and NaN false.
• Other values become true.
• Boolean(value) function
45
Some notes
https://www.w3schools.com/js/js_type_conversion.asp
46
Scope of variables
{
let message = "Hello"; // only visible in this block
alert(message); // Hello
}
alert(message); // Error: message is not defined
47
Exercise
• Declare two variables x and y, assign the value “Big X” to x. Copy the
value from x to y. Show the value of y using alert().
• What is the output of the script?
let name = “javaScript";
alert( `hello ${1}` ); // ?
alert( `hello ${"name"}` ); // ?
alert( `hello ${name}` ); // ?
48
Chapter 4: Operators and Expressions
1
Content
1. Operators
• Assignment operator
• Arithmetic operators
• Bit operators
• Relational / comparison operators
• Logical operators
• Other operators
2. Expression
2
1. Operators
3
Operators
4
Assignment
7
Bit operators
• & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift)
• A = 25 (11001)
B = 20 (10100)
• A&B • A&B ⇒ 16 (10000)
• A|B • A|B ⇒ 29 (11101)
•A^B • A ^ B ⇒ 13 (01101)
• ~A • ~A ⇒ 6 (00110)
• A<<2 • A<<2 ⇒ 100 (1100100)
• A>>2 • A>>2 ⇒ 6 (00110)
8
Comparisons
• Strict equality operator ===: checks the equality without type conversion
alert( 0 == false ); // true
alert( 0 === false ); // false
• For null and undefined value:
• math operators, and < > <= >= operators
• null becomes 0, while undefined becomes NaN
• for == and ===
alert( null === undefined ); // false
alert( null == undefined ); // true, equal each other but not any other value
9
Logical operators
10
Other operators
• Numeric conversion
alert( +true ); // 1
alert( +"" ); // 0
• For String
let s = "my" + "string";
alert(s); // mystring
Other arithmetic operators work only with numbers and always convert their operands
to numbers.
11
Operator precedence
12
Operator precedence
https://developer.mozilla.org/
en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence 13
2. Expression
14
Expression
15
Conditional Expressions
• Comparison operator
16
Conditional Expressions (2)
• Logical operators
17
Expressions vs. Statements
18
Exercises
19
Chapter 5: Statements
1
Content
2
1. Statement, Block of statements
3
2. Declaration and Assignment statements
• let is used to declare a variable: creates the variable and enables to work
with it
• Assignment operator (=) is used to assign a value to it
4
Control structure
• These are instruction structures that specify the program to execute different
commands / scripts, depending on certain conditions.
• Including control flow statements :
• Conditional statement
• if – else,
• switch – case
• Loop statement
• for
• while
• do – while
5
3. Conditional statement
6
if statement
• Syntax
if (condition){
statements;
}
• If the conditional expression (boolean type) gets true, then execute the command
block;
if (year == 2022) {
alert( "That's 2022!" );
alert("Welcome to 2022!" );
}
7
if – else statement
Syntax
if (condition){
‘true’ statements;
}
else {
‘false’ statements;
}
If the conditional expression (boolean type) gets true, then execute the block
‘true’ statements , otherwise, execute the block ‘false’ statements.
if (year == 2022) {
alert('Welcome to 2022!' );
} else {
alert( 'Let \’s choose another year' );
}
8
else-if statement
• Syntax
if (condition_1){
statements;
}
else if (condition_2){
statements;
} else if (condition_3){
statements;
} else {
statements;
}
• Can have many else-if, but one else only if (time < 12) {
alert( 'Too early...' );
} else if (time > 12) {
alert( 'Too late' );
} else {
alert( 'Exactly!' );
}
9
Example - Check for an odd - even number
10
Conditional operator ‘?’
alert( message );
11
switch – case statement
12
switch – case statement(2)
• Syntax :
switch(expression) {
[true]
case x: case a
case a break
[false] action(s)
// code block
break; [true]
case y: case b
[false]
case b
action(s)
break
// code block
break;
.
default: .
.
} case z
[false]
case z
action(s)
break
13
Example
switch (day) {
case 0:
case 1:
rule = “weekend”;
break;
case 2:
case 3:
case 4:
case 5:
case 6:
rule = “weekday”;
break;
default:
rule = “error”;
}
14
4. Loop statement
15
While and do while loops
while (condition) {
// code block to be executed
}
do {
// code block to be executed
}
while (condition);
16
Example
let i = 0; let i = 0;
while (i < 3) { // shows 0, then 1, then 2 do {
alert( i ); alert( i );
i++; i++;
} } while (i < 3);
let i = 3;
while (i) alert(i--);
let i = 0; let i = 0;
while (++i < 5) alert( i ); while (i++ < 5) alert( i );
17
Example(2)
let a = 5,fact = 1;
while (a >= 1){
fact *=a;
a--;
}
alert(“The Factorial of 5 is “+fact);
Replace by do-while ?
18
for loop
• 3 expressions (1) (2) (3) can be absent (replaced with corresponding statements
in the block)
let i = 0;
let i = 0;
for (; i < 3;) {
for (; i < 3; i++) {
alert( i++ );
alert( i );
}
}
• You can declare variables in the for statement
• Usually used to declare a counter variable
• Usually declared in the start expression
• The scope of the variable is limited in the loop
19
Example
for (let i = 0; i < 5; i++) alert( i ); for (let i = 0; i < 5; ++i) alert( i );
20
Use for and while
21
Use for and while (2)
22
Example
let sum = 0;
outer: for (let i=0; i<x; i++) {
inner: for (let j=i; j<x; j++){
sum++;
if (j==1) continue;
if (j==2) continue outer;
if (i==3) break;
if (j==4) break outer;
}
}
23
"for..in" loop
24
for..of, forEach loop
let arr = [“coffee", “tea", “water"]; let fruits = ["coffee", “tea", “water"];
for (let i = 0; i < arr.length; i++) { // iterates over array elements
alert( arr[i] ); for (let fruit of fruits) {
} alert( fruit );
}
25
Exercises
• Write an .html file, to ask user a question, receipt the answer. Check if their
answer is correct, appear a new window to notice them.
• Write a loop which prompts for a number greater than x. If the visitor enters
another number – ask them to input again. (x is entered by user)
• Write the code to print out all prime numbers in the interval from 2 to n. (n is
entered by user)
26
Chapter 6: Function
1
Content
2
1. Function Oriented Programming concept
3
Function Oriented Programming concept
child function
data with
content
Enter the coefficients Calculate delta Calculate the solution
4
Concept of function
5
Function calling
• Calling a function:
• Through its name
• Send input data to the function through parameters
• Run the block of code with input data
• Return output data to the calling program through returned value or
parameters
B() return
call
A()
6
2. Function in JavaScript
• Definition of a function
• function <function-name> (<formal parameters definition>) {
Declare the variables used inside the function
Function statements
[return statement]
}
• Each function needs one and only one definition
• JavaScript is “type less” so no need to define return_type for returned value,
and parameters.
7
Parameters specification
• Parameters/arguments
• in function definition: formal parameters (dummy names) represent
values/variables supplied to the function when it is called
• in function calls: the real parameters passed to this function call
• when a function is called, each formal parameter will be evaluated and
assigned to the coresponding value
d = sum(c, a);
8
Parameters specification
• Parameters/arguments
• when a function is called, each parameter will be evaluated and
assigned to the coresponding value.
• The parameters get value from the real value/variable supplied
(make a copy of value)
9
Pass By Value
function assign10(x){
...
x = 10; x
} 20 10
10
Pass by Reference
changing the value inside the function also change the original value
11
Pass by Reference
} Before a = 10 b = 20 c=undefined
let obj = { Inside a = 40 b = 50 c=CHECK
a: 10, After a = 10 b = 20 c=undefined
b: 20
}
console.log(`Before a = ${obj.a} b = ${obj.b} c=${obj.c}`);
check(obj)
console.log(`After a = ${obj.a} b = ${obj.b} c=${obj.c}`);
12
Default values
• default parameter is evaluated only when the function is called without the
respective parameter.
13
Global and local variables
• Local variable:
• A variable declared inside a function
• only visible inside that function
• and destroyed after the end of the function
function showMessage() {
let message = "Hello, I'm JavaScript!";
alert( message );
}
showMessage(); // Hello, I'm JavaScript!
alert( message ); // <-- Error!
14
Global and local variables
• Outer variables
• A function can access an outer variable
• and modify it
15
Global and local variables
• Outer variables
• If a same-named variable is declared inside the function then it shadows the
outer one.
let userName = 'Peter';
function showMessage() {
let userName = “Mary”; Peter
let message = 'Hello, ' + userName; Hello, Mary
alert(message); Peter
}
alert( userName );
showMessage();
alert( userName );
16
Global and local variables
17
Return specification
18
Return specification
• No return
• the same as if it returns undefined, or return empty
function doNothing1() { /* empty */ }
function doNothing2() {
return;
}
19
3. Advanced technique with functions
20
Function is a value
21
Function Expressions
• in an assignment expression
• a variable sayHi getting a value, the new anonymous function, created as function() {
alert("Hello"); }
• create a function and assign it into the variable sayHi
• Omitting a name is allowed (anonymous)
22
Function Expressions
function showOk() {
alert( "You have booked a flight." );
}
function showCancel() {
alert( "You canceled a flight." );
}
callback functions
24
Callback functions
ask(
"Do you agree to book this ticket?",
function() { alert("You have booked a flight."); },
function() { alert("You canceled a flight."); }
);
25
Arrow functions
26
Arrow functions
welcome();
alert( sum(1, 2) ); // 3
27
Nested functions
• Nested functions:
• A function is called “nested” when it is created inside another function
28
forEach
let sum = 0;
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);
function myFunction(item) {
sum += item;
}
29
Others...
30
Exercises
31
Exercises
32