LU02 Web Tecnologies - JavaScript (Updated 180422)
LU02 Web Tecnologies - JavaScript (Updated 180422)
Learning objectives
In this lesson, you will learn
What is JavaScript? How to call?
What is DHTML?
Dynamic HTML (DHTML)
Makes possible a Web page/app to react and change in response
to the user’s actions, a.k.a “scripting”
DHTML
https://medium.com/@demiansims/javascript-a-brief-timeline-46e8943ef995
8
What is JavaScript?
JavaScript is a scripting language developed by Netscape for
dynamic content
Lightweight, cross-platform
Can be used as object-oriented language system
fi le
es s to OS/
Client-side technology NO acc
JavaScript Advantages
JavaScript allows interactivity such as:
Implementing form validation
React to user actions, e.g. handle keys
Changing an image on moving mouse over it
Sections of a page appearing and disappearing
Content loading and changing dynamically
Performing complex calculations
Custom HTML controls, e.g. scrollable table
Implementing AJAX functionality
10
Can read and write HTML elements and modify the DOM tree
Example 1
first-script.html
<html>
<body>
<script type = “text/javascript”>
alert('Hello JavaScript!');
</script>
</body>
</html>
12
Example 2
small-example.html
<html>
<body>
<script>
document.write('JavaScript rulez!');
</script>
</body>
</html>
How to call/link?
14
Highly recommended
The .js files get cached by the browser (speed page loads)
Readability/modularity (separated and recombined – easier to
read/maintain)
When using the script tag, always use the attribute name and value of
15
When is Executed?
JavaScript code is executed during the page loading or
when the browser fires an event
All statements are executed at page loading
Some statements just define functions that can be called
later
Function calls or code can be attached as "event
handlers" via tag attributes
Executed when the event is fired by the browser
<img src="logo.gif" onclick="alert('clicked!')" />
16
<body>
<img src="logo.gif"
onclick="test('clicked!')" />
</body>
</html>
17
JavaScript’s Syntax
Comments
Values
Objects
Operators
Control flow
Loops
Functions
Errors handling
20
JavaScript Syntax
The JavaScript syntax is similar to C# and Java
Operators (+, *, =, !=, &&, ++, …)
Variables (typeless)
Conditional statements (if, else)
Loops (for, while)
Arrays (my_array[]) and associative arrays
(my_array['abc'])
Functions (can return value)
Function variables (like the C# delegates)
Comments
Single line
use to explain code
// This is a single line comment use before/after code
Similar in C++
Multiple lines
use to explain code
/* This is a comment block where anything inside is
ignore by JavaScript */
Similar in C
22
Data Types
JavaScript data types:
Values
ES6-ECMAScript 2015
Literal – fixed values
const counter = 100; assign value
const pi = 3.14;
String – string of characters
var str1 = "This is a string"; Variable’s
let str2 = ‘This is another string’; name
Array – special variable holding multiple values
var x1 = 1, x2 = 5.3, x3 = "aaa";
var my_array = [1, 5.3, "aaa"];
ES6-ECMAScript 2015
Objects – hash tables, a.k.a {name:value}pairs
const client = {fname:"John", lname:"Doe", age:20};
let statement
brackets {}
{
let myFunc = “hello”;
// myFunc can be used here
}
// myFunc CANNOT be used here
const statement
<script>
function myFunc() {
var x = 5;
var y = 5;
var sum = x + y; //adds x and y
alert(sum); //shows 10
}
</script>
</body>
</html>
Number Methods
toFixed(), toPrecision()
var x = 9.656;
x.toFixed (2); // returns 9.66
x.toPrecision(2); // returns 9.7
Number(), parseInt(), parseFloat()
Number(true); // returns 1
parseInt("10.33"); // returns 10
parseFloat("10 20 30"); // returns 10
toExponential(), isFinite(), isInteger(), valuedOf() and more
29
String Operations
The ‘+’ operator joins strings
var string1 = "fat ";
var string2 = "cats";
alert(string1 + string2); // fat cats
alert(parseInt("9") + 9); // 18
30
String Methods
Length
var string1 = "This is a dummy sentence.";
string1.length; // 24 including white space
indexOf(), lastIndexOf(), search(), match(), etc
string1.indexOf("dummy"); // output?
string1.lastIndexOf("dummy",15); // output?
string1.search("dummy"); // output?
slice(), substring(), substr(), replace(), toUpperCase(), toLowerCase(),
concat(), trim(), and more
31
<script>
var cities = ["Kuching", "Samarahan", "Bintulu"];
document.getElementById ("demo").innerHTML = cities;
</script>
</body>
</html>
Get Length of an Array- Sample
ArrayLen.html
<!DOCTYPE html>
<html>
<head>
<title> Get Array’s Length</title>
</head>
<body>
<p id = "demo"></p>
<script>
var cities = ["Kuching", "Samarahan", "Bintulu"];
document.getElementById ("demo").innerHTML = cities.lenght;
</script>
</body>
</html>
34
Array Operations
Appending an element, getting the last element, getting
array length:
var arr = [1, 2, 3, 4, 5];
arr.push(9); // 1,2,3,4,5,9
arr.length; // 6
arr.pop(); // 1,2,3,4,5
arr.length; // 5
Finding element's index in the array:
arr.indexOf(3); // 2
35
Array Methods
concat()
var arr1 = ["John", "Jane"];
var arr2 = ["Ben", "Belle", "Bob"] ;
var nameDB = arr1.concat(arr2); // output?
sort()
var fruits =["apple","orange","durian", "banana"];
fruits.sort(); // output?
document.write(fruits)
Confirmation box
Contains text, [OK] button and [Cancel] button:
confirm("Are you sure?");
Prompt box
Contains text, input field with default value:
prompt ("enter amount", 10);
concat()
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function myFunction() {
var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var children = hege.concat(stale);
document.getElementById("demo").innerHTML = children;
}
</script>
</body>
</html>
sort()
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
function myFunction() {
fruits.sort();
document.getElementById("demo").innerHTML = fruits;
}
</script>
</body>
</html>
39
Object
Primitive data type – store single value
Object – complex and contain combination of the primitive
data types
in the form of “key:value” pairs
var uni = {
name: "UNIMAS",
location: "Sarawak",
established: 1992
};
Assessing object
By name/key
uni.established; or
uni["established"]; // 1992
In loop
var i, txt ="";
For(i in uni){
txt += uni[i] + " ";
};
Using Object.values()
var myArr = Object.values(uni);
JSON.stringify()
var myStr = JSON.stringify(uni);
Object methods
Adding method to object
uni.fullName = function(){
return this.name + " " + this.location;
};
Special Objects
Math Object
Methods – abs(), atan(), random(), and more
Date Object
4 ways to initiate
var d = new Date();
var d = new Date(miliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes,
seconds, miliseconds);
Operators
Arithmetic
Comparison
Logical
Bitwise
https://www.digitalocean.com/community/tutorials/javascript-
unary-operators-simple-and-useful
44
Arithmetic
var x = 30, y = 3;
x + y returns 33
x – y returns 27
x * y returns 90
x / y returns 10
x % y returns 0
x ** y returns 27000
x++ returns 30 (return value before increment)
++x returns 31 (return value after increment)
x-- returns 30 (return value before decrement)
--x returns 29 (return value after decrement)
-x returns -30 (negation)
+true returns 1 (convert non-numbers into numbers)
45
x == y is not true
x != y is true
x > y is true
x < y is not true
x >= y is true
x <= y is not true
x === y is not true (value & type must be equal)
x !== y is true (value & type not equal)
a && b is false
a || b is true
!(a && b) is true
for details
46
Bitwise
var x = 2, y = 3;
x & y returns 2
x | y returns 3
~x returns -3
x ^ y returns 1
x << y returns 16
x >> y returns 0
x >>> y returns 0
for details
47
Control flow
if…
if…else
if…else if
switch
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/
Building_blocks/conditionals
48
Syntax
if (expression) { if
Execute if expression is true
}
if (expression) {
Execute if expression is true
If…else
} else {
Execute if expression is false
}
if (expression A) {
Execute if expression A is true If…else if…
} else if (expression B) {
Execute if expression B true
} else {
Execute if all expression is false
}
49
conditional-statements.html
var a = 0;
var b = true;
if (typeof(a)=="undefined" || typeof(b)=="undefined") {
document.write("Variable a or b is undefined.");
}
else if (!a && b) {
document.write("a==0; b==true;");
} else {
document.write("a==" + a + "; b==" + b + ";");
}
51
Syntax - switch
The switch statement works like in C#:
switch (expression) {
case 1: This is how it works:
• The switch expression is evaluated once.
// do something • The value of the expression is compared
break; with the values of each case.
case 'a': • If there is a match, the associated block of
code is executed.
// do something else
break;
case 3.14:
// another code
break;
default:
// something completely different
}
52
Switch Statement
between 0 and 6.
(Sunday=0, Monday=1, Tuesday=2 ..)
weekday name:
<html>
<body>
switch-statements.html 53
<p id="demo"></p>
<script>
var day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script> </body></html>
54
Loops
for loop
for…in loop
for…of loop
while loop
do … while loop
55
do {
text += “<br>The number is " + i;
i++;
}
while (i < 4);
57
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For/In Loop</h2>
<p>The for/in statement loops through the properties of an object.</p>
<p id="demo"></p>
<script>
var txt = "";
var person = {fname:"John", lname:"Doe", age:25};
var x;
for (x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
Break & Continue
break;
use to exit the switch() or loop
break labelname;
use to exit labelname code block
Functions
https://www.toolsqa.com/javascript/functions-in-javascript/
60
Function - declaration
Define once and re-use
Code structure – splitting code into parts
Data comes in, processed, result returned
Parameters come in
function average(a, b, c) here.
{
var total; Declaring variables
total = a+b+c; is optional. Type is
return total/3; never declared.
}
Value returned
here.
61
Function - expression
Define using expression
// function expression in ES5 Function without a name
var X = function (a, b, c)
{
return (a+b+c)/3; As function expression is
}; stored in a variable,
var Y = X(1,2,3); variable is used as
function
// arrow function in ES6
const x = (a, b, c) => (a+b+c)/3;
Passing function as argument to another function
62
Function - arguments
Pass by value – not visible outside function
myFunc(mycar);
y = mycar.make; // ‘Perodua’ as changed by function
64
function sum() {
var sum = 0;
for (var i = 0; i < arguments.length; i ++)
sum += parseInt(arguments[i]);
return sum;
}
alert(sum(1, 2, 4)); functions-demo.html
65
</html>
68
function calc() {
var result;
result = add(3,5); // can prompt for user input
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "calc()" value = "Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>}
69
Error handling
Common mistakes
try statement
catch statement
throw statement
finally statement
70
Syntax
try { Define error check
code block to check for errors
throw () Customised exception
}
catch (err) { Handle error
code block to handle errors
}
finally { Must run code
code block that always execute
}
71
Example (try…catch…throw…finally)
<script type = "text/javascript">
function calcSum() { Define error check
value1 = document.getElementById("txt1").value;
value2 = document.getElementById("txt2").value;
try{
if(value1 == "") throw ("Value 1 is empty");
if(isNaN(value1)) throw ("Value 1 is not a number");
else{
if(value2 == "") throw ("Value 2 is empty");
if(isNaN(value1)) throw ("Value 2 is not a number");
}
} Customised
catch (e){
alert("Error: " + e ); Display error
}
finally{
var sum = parseInt(value1) + parseInt(value2);
alert(sum)
}
} Must run code
</script>
72
Example (try…catch…throw…finally)
<body>
<form name="calform">
<p>Enter 1st number: <input type="text" name="textbox1"
id="txt1"><br /></p>
<p>Enter 2nd number: <input type="text" name="textbox2"
id="txt2"><br /></p>
<button onclick="calcSum()"/>Calculate two numbers</button>
</form>
</body>
</html>
List of errors
Syntax Error
missing ( or ), { or }
Range Error
invalid/out of range
Reference Error
reference/assignment to undefine X
Type Error
is not a function/object; can’t access/define/delete…
Warning
…common mistakes and detail of errors
JavaScript HTML DOM
https://www.tutorialspoint.com/javascript
/javascript_html_dom.htm
https://www.w3schools.com/jsref/dom_obj_document.asp
75
DOM Manipulation
Once can access an element, can read and write its
attributes HTML element
function change(state) { with id=lamp
var lampImg = document.getElementById("lamp");
lampImg.src = "lamp_" + state + ".png";
var statusDiv = document.getElementById("statusDiv");
statusDiv.innerHTML = "The lamp is " + state";
HTML element
if(state==“on”){} with id=statusDiv
if(state==“off”){}
}
… property method
<body bgcolor="gray">
<img width="200px" height="300px" id="lamp" src="lamp_off.png"/><br/>
<div id="statusDiv"> Mouse over the switch!</div>
<img width="40px" height="60px" src="switch.png"
onmouseover="change('on')" onmouseout="change('off')" />
77
Finding Elements
Access elements via ID
var x = document.getElementById("some_id”);
DOM Navigation
https://data-flair.training/blogs/javascript-events/
83
Animation events:
animationstart, animationiteration, animationend
87
Miscellaneous events
onload, onunload
Allowed only for the <body> element
Fires when all content on the page was loaded / unloaded
88
<script>
function mouseDown() {
document.getElementById("myP").style.color = "red";
}
function mouseUp() {
document.getElementById("myP").style.color = "green";
}
</script>
</body></html>
89
Browser APIs
DOM, AJAX, Web Audio, Geolocation,
validation, etc
Conclusion
?
?
?
Questions?
?
?
?
?
? ?