05 JavaScript 27feb 6march
05 JavaScript 27feb 6march
Adding JavaScript
Events
Form Validation
2
C L I E N T- S I D E S C R I P T I N G
3
W H AT I S J AVA S C R I P T
4
Source: Wikipedia ECMAScript
JAVASCRIPT HISTORY
• ECMAScript 5 was released in 2009 and ECMAScript 2015 (the 6th edition) was
released in 2015.
• At the moment, ECMAScript 2025 (the 16th edition) is the latest stable release.
5
WHERE TO PLACE JAVASCRIPT?
• When the browser encounters a block of JavaScript, it generally runs it in order, from
top to bottom. This means that you need to be careful what order you put things in the
web page.
– Order of the JavaScript code and order of the JavaScript w.r.t HTML statements.
6
INLINE JAVASCRIPT
• Inline JavaScript refers to add the JavaScript code directly within certain HTML
attributes.
7
EMBEDDED JAVASCRIPT
<script>
function myFunction() {
[Link]("demo").innerHTML = "Paragraph changed.";
}
</script>
8
EXTERNAL JAVASCRIPT
• JavaScript supports this separation by allowing links to an external file that contains the
JavaScript.
• You can place an external script reference in <head> or <body> as you like.
• The script will behave as if it was located exactly where the <script> tag is located.
<head>
<script src="[Link]">
</script>
</head>
9
THE JAVASCRIPT
LANGUAGE
B A S I C SY N TA X
• Semicolon
– JavaScript generally does not require semicolons if just has only one statement on a line.
– If you place more than one statement on a line, you must separate them with semicolons.
11
VARIABLES
• Variables in JavaScript are dynamically typed, meaning a variable can be an integer, and then
later a string, then later an object, if so desired.
• This simplifies variable declarations as we do not require to give the type during declaration.
Instead, we use var and let keywords to declare the variables.
var x = 5;
var y = 6;
var z;
let sum = 2;
• Variable names are case-sensitive.
• The first character of a variable name can be only a-z, A-Z, $, or _ (no numbers).
• Suggestions by W3School
– camelCase is used by JavaScript itself, by jQuery, and other JavaScript libraries.
– Do not start names with a $ sign. It will put you in conflict with many JavaScript library names.
12
DIFFERENCE BETWEEN VAR AND LET
• As it is related to the scope concept, more explanation and examples will be given
when we talk about the Variable Scope.
13
NUMBERS
• There are three special values in JavaScript that are considered numbers but don’t
behave like normal numbers.
– Infinity, ⎼Infinity, and NaN
• JavaScript does not raise overflow, underflow, or division by zero errors.
• A result of computation results in a number larger than the allowed value ➔ Infinity
14
STRINGS
• JavaScript string variables are enclosed within a matched pair of single quotes or
double quotes or backticks.
– 'Single quotes'
– "Double quotes"
– `Backticks` - template literal
• You may include a single quote within a double-quoted string or vice versa. But you
must escape a quote of the same type by using backslash character.
– "Say \"Cheer!\""
15
BACKTICKS
– String interpolation
• We can avoid the concatenation operator by using placeholders of the form ${expression} to perform
substitutions for embedded expressions
var a = 5;
var b = 10;
[Link](`Fifteen is ${a + b} and not ${2 * a + b}.`);
// "Fifteen is 15 and not 20."
16
[Link]
WORKING WITH STRINGS
• Use the + operator to concatenate • Use the length property to get the
strings length of a string
17
BOOLEAN
18
C O M PA R I S O N O P E R ATO R S
20
A R R AY
• The index of the first element is 0, and the highest possible index is 232 – 2
• Every array has a length property. It returns the number of array elements.
21
[Link]
A R R AY M E T H O D S
Method Description
concat() joins two or more arrays, and returns a copy of the joined arrays
push() adds new elements to the end of an array, and returns the new length
shift() removes the first element of an array, and returns that element
unshift() adds new elements to the beginning of an array, and returns the new length
22
CONDITIONALS
23
CONDITIONS
a ? b : c
24
LOOPS
25
LOOPS [Link]
[Link]
ate_forof
26
FUNCTIONS
27
F U N C T I O N D E C L A R AT I O N
• They are defined by using the reserved word function and then the function name,
(optional) parameters, and the body of the function (enclosed in curly braces).
• Since JavaScript is dynamically typed, functions do not require a return type, nor do
the parameters require type.
28
FUNCTION EXPRESSION
• To call the function, we call the variable name with necessary arguments.
29
ARROW FUNCTION
• Instead of using the function keyword, we use an arrow => to declare a function.
• Without argument:
var HW = () => { [Link]("Hello World"); };
() => { statements }
30
VARIABLE SCOPE
31
GLOBAL SCOPE
• Variables declared within a function (by var or let) have the FUNCTION scope.
• Variables declared with var or let keywords are quite similar when declared inside a
function.
33
BLOCK SCOPE
• Variables declared with the var • Variables declared with the let
keyword cannot have Block Scope. keyword can have Block Scope.
• Variables declared inside a block { • Variables declared inside a
} can be accessed from outside the block { } cannot be accessed
block. from outside the block:
{ {
var B = 2; let B = 2;
} }
// B CAN be accessed here // B can NOT be accessed here
• Constants are block-scoped, much like variables defined using the let statement.
var x = 10;
// Here x is 10
{
const x = 2; [Link]
// Here x is 2
}
// Here x is 10
35
FUNCTION CLOSURE
• A closure is the combination of a function and the lexical environment within which
that function was declared.
– This environment consists of any variables that were in-scope at the time the function
closure was created.
• Closures are useful because they let you associate some data (the lexical
environment) with a function that operates on that data.
36
FUNCTION CLOSURE
Example 1 Example 2
37
JAVASCRIPT OBJECTS
• We group related data and functions (methods) into a single object, which represents
information about the thing we are trying to model, and functionality or behavior that we
want it to have.
38
C R E AT E A N O B J E C T
• Each name/value pair must be separated by a comma, and the name and value in each
case are separated by a colon.
39
W H AT I S ‘ T H I S ’ ?
greeting: function() {
alert('Hi! I\'m ' + [Link] + '.');
}
• Within the body of a method, 'this' evaluates to the object on which the method was
invoked.
– In the above example, this refers to the person object.
• In the global execution context (outside of any function), this refers to the global
object, i.e. the window object in the HTML.
• In a function that is not related to an object, this refers to the global object (in non-
strict mode) or undefined (in strict mode).
– This applies even when the function is nested inside an object’s method.
40
C R E AT E A N O B J E C T
• JavaScript uses special functions called constructor functions to define new objects and their
features.
• To create an object, we use the new keyword.
• JavaScript has a built-in method called create() that allows you to create a new object
based on any existing object.
• To create a new object, simply pass the desired prototype object as an argument to the
[Link]() method.
42
B R AC K E T N OTAT I O N
• In previous examples, we used the dot notation to access an object’s properties and
methods.
[Link]
[Link]
boy["age"];
boy["name"]["first"]
• This looks very similar to how we access the items in an array, instead of using an index
number to select an item, you are using the name associated with each member's
value.
– It is the reason why objects are sometimes called associative arrays.
43
D Y N A M I C A L LY A D D O B J E C T M E M B E R S
man['eyes'] = 'hazel';
[Link] = function() { alert("Bye everybody!"); }
44
DESTRUCTURING ASSIGNMENT
STAT E M E N T
const member = {id: '32156', name: 'Eroo Guu', alias: 'EG', status: 'active'};
const {id, alias} = member;
const {name: user} = member;
[Link](id); //- '32156'
[Link](alias); //- 'EG'
[Link](user); //- 'Eroo Guu' 45
S P R E A D SY N TA X ( … A B C )
• … is a versatile tool that simplifies a variety of operations involving arrays and objects
• Function arguments
const numbers = [1, 2, 3]; function myFunction(v, w, x, y, z) {}
[Link](...numbers); // 3 const args = [0, 1];
myFunction(-1, ...args, 2, ...[3]);
• Concatenate arrays
let arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
46
S P R E A D SY N TA X ( … A B C )
47
THE WINDOW OBJECT
• The window object is supported by all browsers. It represents the browser's window.
• There can be several window objects at a time, each representing an open browser
window.
• Global variables are properties of the window object. Global functions are methods of
the window object.
• Even the document object (of the HTML DOM) is a property of the window object.
48
[Link]
THE WINDOW OBJECT
• The window object has a number of properties and methods that we can use to
interact with it.
Property /method Description
document Returns the Document object for the window
history Returns the History object for the window
location Returns the Location object for the window
alert() Displays an alert box with a message and an OK button
close() Closes the current window
focus() Sets focus to the current window
open() Opens a new browser window
prompt() Displays a dialog box that prompts the visitor for input
resizeTo() Resizes the window to the specified width and height
49
T R Y. . . C AT C H . . . F I N A L LY S TAT E M E N T
• The try statement allows you to define a block of code to be tested for errors while
it is being executed.
• The finally statement lets you execute code, after try and catch, regardless of the
result.
50
T R Y. . . C AT C H . . . F I N A L LY S TAT E M E N T
• Syntax
try {
tryCode - Block of code to try
} The catch-block specifies an
catch(err) { identifier (err in the example) that
catchCode - Block of code to handle errors holds the value of the exception; this
} value is only available in the scope of
finally { the catch-block.
finallyCode - Block of code to be executed
regardless of the try / catch result
}
[Link]
51
I M P O R T A N D E X P O R T STAT E M E N T S
52
EXPORTING
IMPORTING
Import
• import { nameX, nameY } from '[Link]';
54
[Link]
DAT E A N D T I M E
• new Date([Link]() + 3600000) – returns a Date object with time 1 hour in the future
let BD = new Date("2020", "11", "31"); //create a Date object for 31/12/2020
[Link]([Link]()); //- 2020
[Link]([Link]()); //- 11, which means December
[Link]([Link]()); //- 31
[Link]([Link]()); //- 1609344000000
55
S E T I N T E R V A L ( ) A N D S E T T I M E O U T( )
[Link] [Link]
l ml
56
DOM – THE
DOCUMENT OBJECT
MODEL
THE DOM
• The Document Object Model (DOM) is a programming interface for HTML documents.
• The DOM represents a web document as nodes and objects, that allows us to make
use of programs to manipulate the content and appearance of the web document.
58
DOM NODES <!doctype html>
<html>
<head>
<title>COMP3322 Test Page</title>
</head>
<body>
<h1>Welcome Guys!</h1>
<p>Hello, I am Anthony and this is my course simple home page.</p>
• DOM serves as a map to all the elements <p>To access the course's Moodle site, please visit
<a href=
on the HTML document. "[Link]
</body>
– In the DOM, each element within the HTML </html>
59
DOM NODES
• All of the properties, methods, and events available for manipulating and creating web
pages are organized into node objects.
– e.g., the document object represents the document, the table object implements the DOM
interface for accessing HTML tables, etc.
• Most of the tasks that we typically perform in JavaScript involve finding a node object,
and then accessing or modifying it via those properties and methods.
60
BASIC NODE PROPERTIES
• Each node has a number of basic properties that you can examine or set.
Property Description
attributes Collection of node attributes
childNodes A NodeList of child nodes for this node
firstChild First child node of this node.
lastChild Last child of this node.
nextSibling Next sibling node for this node.
nodeName Name of the node
nodeType Type of the node
nodeValue Value of the node
parentNode Parent node for this node.
previousSibling Previous sibling node for this node.
61
BASIC NODE METHODS
• Which of these are valid depends on the node’s position in the HTML and
whether it has parent or child nodes.
Property Description
[Link](A) Append the new node A as the last child.
[Link]() Clone a node, and optionally, all of its contents, i.e., include any child
nodes of the original node.
[Link]() Returns a boolean indicating if the element has any child nodes, or not.
[Link](A,B) Inserts node A as a child before the reference child node B specified in
the call.
[Link](Y) Returns a Boolean value indicating whether or not the two nodes X & Y
are the same.
[Link](A) Removes child node A from node X.
[Link](A,B) Replaces child node B with the node A. 62
DOCUMENT OBJECT
• The document object is the root JavaScript object representing the entire HTML
document, and more often it serves as the starting point for our DOM crawling.
• It is the child of the window object. We can use [Link] to refer to the
document object, or simply refer to document.
• The document object comes with a number of properties and methods for accessing
collections of elements.
• Example:
63
DOCUMENT OBJECT
65
ACCESSING ELEMENT NODES
<!doctype html>
<html>
<head>
<title>COMP3322 Test Page</title>
<style>
#header { background-color: yellow;}
</style>
</head>
<body>
<h1 id="header">Welcome Guys!</h1>
<p>Hello! I am Anthony and this is my course simple home page.</p>
<p class="moodle">To access the course's Moodle site, please visit
<a href="[Link]
</body>
</html>
var elm = [Link]('p');
• Element objects implement the DOM Element interface, which has its own set of
properties and methods.
67
[Link]
68
AC C E S S I N G E L E M E N T AT T R I B U T E S
<!doctype html>
<html>
<head>
<title>COMP3322 Test Page</title>
<style>
#header { background-color: yellow;}
</style>
</head>
<body>
<h1 id="header">Welcome Guys!</h1>
<p>Hello! I am Anthony and this is my course simple home page.</p>
<p class="moodle">To access the course's Moodle site, please visit
<a href="[Link]
</body>
</html>
var lnk = [Link][0].href;
<script>
var para = [Link]('p');
var text = [Link]('My phone no. is: 2859 7073');
[Link](text);
var refNode = [Link]('p');
refNode[0].insertAdjacentElement('afterend', para);
</script>
70
ADDING CONTENT
<body>
<h1 id="header">Welcome Guys!</h1>
<p>Hello! I am Anthony and this is my course simple home page.</p>
<p class="moodle">To access the course's Moodle site, please visit
<a href="[Link]
</body>
71
CHANGING ELEMENT
STYLES
[Link]('header').[Link] = 'blue';
[Link]('p').[Link] = "red";
[Link]('a').[Link] = "green";
[Link]('h1')[0].[Link] = "250px";
72
ACCESSING DOM OBJECTS USING
JAVASCRIPT
<body> <body>
<script> <script src='[Link]'></script>
try { <p>This is the original paragraph</p>
let para = [Link]('p'); </body>
[Link] = 'Replace the original paragraph';
} catch(err) { [Link]
try {
[Link]('Error in accessing the paragraph');
let para = [Link]('p');
}
[Link] = 'Replace the original paragraph';
</script>
} catch(err) {
[Link]('Error in accessing the paragraph');
<p>This is the original paragraph</p>
}
</body>
• 2nd Example
<body>
<script defer src='[Link]'></script>
<p>This is the original paragraph</p>
</body>
• The defer attribute tells the browser not to wait for the script and continue to process
the HTML and build DOM.
– The script loads “in the background”, and then runs the script when the DOM is fully built but
before DOMContentLoaded event
• The DOMContentLoaded event fires when the initial HTML document has been completely loaded and
parsed, without waiting for stylesheets, images, and subframes to finish loading
74
< S C R I P T > TAG – A SY N C AT T R I B U T E
<body>
<p>This is the original paragraph</p> Try to
<div></div> remove async
• async scripts load in the <script async src='[Link]'></script>
<script>
background (like defer) but run try {
let now = new Date();
let text = [Link]('div').innerHTML;
immediately when ready let para = [Link]('p');
[Link] = `At ${[Link]([],{hour: 'numeric',
– The DOM and other scripts don’t minute: 'numeric', second: 'numeric’, fractionalSecondDigits: 3})},
replace the original paragraph. `+text;
wait for async script, and they don’t } catch(err) {
[Link](err);
wait for anything }
</script>
– DOMContentLoaded event may <p>This is the last paragraph.</p>
</body>
happen both before and after [Link]
async, no guarantees here try {
let time = new Date();
let first = [Link]('div');
[Link] [Link] = `At ${[Link]([],{hour: 'numeric',
minute: 'numeric', second: 'numeric', fractionalSecondDigits: 3})}, I add
this line.`;
} catch(err) {
[Link](err);
75
}
EVENT HANDLING
EVENTS
• When system detects an event, it fires a signal of some kind/form and some action can
be automatically taken to handle the event.
77
EVENT HANDLERS
• Each available event has an event handler, which is a block of code (usually a
JavaScript function) that will be run when the event fires.
[Link] = function() {
/* Any code placed here will run when the user
clicks anything within the browser window */
};
• When such a block of code is defined to be run in response to an event firing, we say
we are registering an event handler.
78
COMMON WEB EVENTS
• Mouse events
79
COMMON WEB EVENTS
Attribute Event Description
• Window events onerror error An error occurs when the document or an image
loads.
onDOMContentLoad DOMContentLoad The HTML document has been completely parsed,
and all deferred scripts have downloaded and
executed
onload load A page (including all images) is finished loading.
onresize resize Fires when the browser window is resized.
onunload unload When another page is loaded or when the browser
window is closed.
• There are three common methods for applying event handlers to elements within web
pages:
– As an HTML attribute
– As a method attached to the element
– Using addEventListener( )
81
A S A N H T M L AT T R I B U T E
[Link]
82
[Link]
AS A METHOD
• This approach has the benefit of simplicity and ease of maintenance, but has a major
drawback.
– We can bind only one event handler to an element at a time with this method.
83
[Link]
USING ADDEVENTLISTENER()
• This approach allows us to keep the logic within the scripts and allows us to perform
multiple bindings on a single object.
– Both handlers would run when the event occurs. 84
[Link]
REMOVEEVENTLISTENER()
85
EVENT OBJECT
• No matter which type of event we encounter, they are just another type of DOM
objects and the event handlers associated with them can access and manipulate them.
• Typically we see the events passed to the function handler as a parameter named e,
evt, or event.
function someHandler(e) {
// e is the event object, which represents the event that triggered this
handler.
}
86
[Link]
E V E N T P R O PAG AT I O N – B U B B L I N G
• In that case, one user action can trigger multiple event handlers in action.
87
[Link]
E V E N T P R O PAG AT I O N – C A P T U R I N G
• Then it moves on to the next element inside <html> and does the same thing,
then the next one, and so on until it reaches the onclicked element.
88
[Link]
EVENT OBJECT
89
FORM VALIDATION
V A L I D AT I N G F O R M S – C L I E N T- S I D E
• Client-side validation is validation that occurs in the browser, before the data being
submitted to the server.
– Doing that on the client side will reduce the number of incorrect submissions, thereby reducing
server load.
• There are a number of common validation activities including email validation, number
validation, and data validation.
• With HTML5, form validation becomes much easy.
– This generally does not require JavaScript.
– Most modern browsers support this feature.
– However, the behavior is more or less depended on the browsers.
• Using JavaScript, we can have more control and customization of the validation in the
client-side.
91
HTML5 FORM ELEMENTS (RECAP)
Text
Email
Textarea
URL
Password
Checkbox Date
Select
92
H T M L B U I LT- I N V A L I D A T I O N
• Most of the input are text contents, numbers, strings with special patterns, is
required or not, etc.
• HTML uses validation attributes on form elements to validate most user input.
– With the attributes, we can specify rules such as:
• A required field is still empty. required
93
EXAMPLE
Specifies the
HTML maximum number of
characters allowed
<h1>Account Registration Form</h1>
<form id="RegForm">
<p>
<label for="name">Student Name:</label> The min & max attributes
<input type="text" id="name" name="name" maxlength="50" required> specify the minimum and
</p> maximum value for an
<p>
<label for="number">Student No.:</label> input
<input type="text" id="number" name="number" maxlength="10" pattern="3015[0-9]{6}" required>
</p>
<p>
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="17" max="30" step="1" pattern="[0-9]+">
</p>
<p>
<label for="email">Student Email:</label> Specifies that an input
<input type="email" id="email" name="email" required> field must be filled out
</p> before submitting the
<input class="bttn" type="submit" value="Submit">
<input class="bttn" type="reset">
form
</form>
EXAMPLE
With 10 numerical
characters starting with
HTML '3015'
<h1>Account Registration Form</h1>
<form id="RegForm">
<p>
<label for="name">Student Name:</label>
<input type="text" id="name" name="name" maxlength="50" required>
</p>
<p>
<label for="number">Student No.:</label>
<input type="text" id="number" name="number" maxlength="10" pattern="3015[0-9]{6}" required>
</p>
<p>
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="17" max="30" step="1" pattern="[0-9]+">
</p>
<p>
<label for="email">Student Email:</label>
<input type="email" id="email" name="email" required>
</p> Must be a number
<input class="bttn" type="submit" value="Submit"> with 1 or more [Link]
<input class="bttn" type="reset">
</form>
digit
H T M L B U I LT- I N V A L I D A T I O N
• If the input data doesn’t satisfy the prescribed rule, it is considered invalid; otherwise, it
is considered valid.
• With the valid / invalid status, we can make use of the built-in CSS pseudo-class for the
visualization.
96
EXAMPLE If the input element is in
invalid status, sets the
border to dashed red
CSS color
<style>
label {
display: inline-block;
width: 110px;
}
.bttn{
display: inline-block;
width: 80px;
}
input:invalid {
border: 1px dashed red;
} If the input element is in
input:valid { valid status, sets the
border: 2px solid black; border to black color
}
</style>
[Link]
C U STO M I Z AT I O N
• The purpose is for us to check the state of a form element; given the state, we can take
appropriate actions.
98
[Link]
C O N ST R A I N T VA L I DAT I O N A P I
99
[Link]
– Manipulating Documents
• [Link]
side_web_APIs/Manipulating_documents
102
REFERENCES
• [Link]
– JavaScript Tutorial
• [Link]
• JavaScript Info
– [Link]
103