0% found this document useful (0 votes)
3 views103 pages

05 JavaScript 27feb 6march

The document provides an overview of JavaScript, including its history, syntax, and key features such as the Document Object Model (DOM), events, and form validation. It covers the basics of the JavaScript language, including data types, variables, functions, and control structures like loops and conditionals. Additionally, it explains the differences between variable declarations (var, let, const) and introduces concepts like closures and scope.

Uploaded by

patrick leung
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views103 pages

05 JavaScript 27feb 6march

The document provides an overview of JavaScript, including its history, syntax, and key features such as the Document Object Model (DOM), events, and form validation. It covers the basics of the JavaScript language, including data types, variables, functions, and control structures like loops and conditionals. Additionally, it explains the differences between variable declarations (var, let, const) and introduces concepts like closures and scope.

Uploaded by

patrick leung
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVASCRIPT

2025/26 COMP3322 MODERN TECHNOLOGIES ON WWW


CONTENTS
JavaScript and its history

Adding JavaScript

The JavaScript language

The Document Object Model (DOM)

Events

Form Validation

2
C L I E N T- S I D E S C R I P T I N G

• Let the client compute

3
W H AT I S J AVA S C R I P T

• JavaScript runs right inside the browser.

• JavaScript is dynamically typed scripting language.

• JavaScript is object-oriented in that almost everything in the language is an object


– The objects in JavaScript are prototype-based rather than class-based, which means that while
JavaScript shares some syntactic features of PHP, Java or C#, it is also quite different from
those languages.

4
Source: Wikipedia ECMAScript
JAVASCRIPT HISTORY

• JavaScript was introduced by Netscape in their Navigator browser back in 1995.

• JavaScript is in fact an implementation of a standardized scripting language called


ECMAScript

• In 1998, ECMAScript 2 was released.

• In 1999, ECMAScript 3 was released.


• Which evolved into what is today’s modern JavaScript.

• 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?

• JavaScript can be linked to an HTML page in a number of ways.


– Inline
– Embedded in the document
– Link to an external file

• 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.

• Inline JavaScript is a real maintenance nightmare.

<a href="JavaScript:OpenWindow();">more info</a>


<input type="button" onclick="alert('Are you sure?');">

7
EMBEDDED JAVASCRIPT

• Embedded JavaScript refers to the practice of placing JavaScript code within a


<script> element.

• You can place any number of scripts in an HTML document.

• Scripts can be placed in the <body>, in the <head>, or in both.

<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.

• By convention, JavaScript external files have the extension .js.

• 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.

• JavaScript has two ways of writing comments.


– To write a single-line comment, we can use two slash characters (//).
– To write a block comment, we write the comment between /* and */ pair.

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

• let was introduced in ECMAScript 2015

• It is similar to var when is used in functions.


– They both declare variables that are local to the function.
– A variable declared in a function cannot be accessed or visible outside the function.

• However, let behaves differently within a block of code (delimited by { } ) when


compared to var.

• As it is related to the scope concept, more explanation and examples will be given
when we talk about the Variable Scope.

13
NUMBERS

• All numbers in JavaScript are represented (stored) as floating-point values.

• JavaScript uses 64 bits to store a numerical value.

• 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

• A negative value larger than the allowed negative value ➔ -Infinity

• Division by zero ➔ Infinity or –Infinity

• Zero divides zero ➔ NaN and Infinity divides infinity ➔ NaN

14
STRINGS

• A string is an immutable ordered sequence of 16-bit Unicode characters.

• 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

• Template literal can be used for


– Multi-line string

`string text line 1


string text line 2`

– 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

• There are a number of methods you


can invoke on strings, for example:

17
BOOLEAN

• We can also assign a variable a true or false value.

• JavaScript supports three logical operators on Boolean variables (and expressions):


– and (&& operator),
– or (|| operator), and
– not (! operator).

• Everything in JavaScript has either an inherently “true” or “false” value.


– null, undefined, 0, and empty strings ("") are all inherently false, while every other value is
inherently true.

18
C O M PA R I S O N O P E R ATO R S

Operator Description Matches (x=9)


== Equals (x==9) is true
(x=="9") is true

=== Exactly equals, including type (x==="9") is false


(x===9) is true

<,> Less than, Greater Than (x<5) is false


<= , >= Less than or equal, greater than or (x<=9) is true
equal
!= Not equal (4!=x) is true
!== Not equal in either value or type (x!=="9") is true
(x!==9) is false
19
NULL AND UNDEFINED

• null is a keyword that evaluates to a special value that is


usually used to indicate the absence of a value.
– In JavaScript, the data type of null is an object.

• undefined represents a variable without a value.


– It is the value of variables that have not been initialized.
– The value you get when you query the value of an object
property or array element that does not exist.
– The undefined value is also returned by functions that have no
return value, and the value of function parameters for which no
argument is supplied.

20
A R R AY

• Two ways of creating an array:

• JavaScript arrays are untyped.


– Elements in the same array may be of different types.
– This allows you to create complex data structures, such as arrays of objects and arrays of
arrays.

• JavaScript arrays are dynamic.


– They grow or shrink as needed.

• 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

join() joins all elements of an array into a string

push() adds new elements to the end of an array, and returns the new length

reverse() reverses the order of the elements in an array

shift() removes the first element of an array, and returns that element

sort() sorts the elements of an array

splice() adds/removes elements from an array

toString() converts an array to a string, and returns the result

unshift() adds new elements to the beginning of an array, and returns the new length

22
CONDITIONALS

• JavaScript’s syntax is almost identical • switch statements


to that of PHP, Java, or C when it
comes to conditional structures.

• if and if else statements

23
CONDITIONS

• The ternary operator ? :

a ? b : c

24
LOOPS

• for loops • while loops

25
LOOPS [Link]

[Link]
ate_forof

• for…of loops • for…in loops


– The for...of statement – The for...in statement
creates a loop iterating over iterates over all enumerable
iterable objects, e.g., String, properties of an object that
Array, array-like objects, have strings as keys.
Map, Set, etc.
var person = {fname:"John", lname:"Doe",
age:25};
var cars = ['BMW', 'Volvo', 'Mini'];
element iterable var text = "";
for (let x of cars) { object key
[Link](x + "<br >"); for (let x in person) {
} text += person[x] + " ";
}

26
FUNCTIONS

• When a JavaScript statement is included in a page, the browser executes that


JavaScript statement as soon as it is read except the code fragment is in a function. It
only runs when it is called.

• There are three ways to create a function:


– Function declaration
– Function expression
– Arrow function

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).

function name(parameter1, parameter2, parameter3) {


code to be executed
}

• Since JavaScript is dynamically typed, functions do not require a return type, nor do
the parameters require type.

28
FUNCTION EXPRESSION

• A function is created with the keyword function and is assigned as an expression to a


variable.

• We can create a function without giving it a name (anonymous function).

• 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 }

• With one argument:


var square = a => { return a*a; };
arg1 => { statements }
(arg1) => { statements }
var multiply = (x, y) => { return x * y; };
• Multiple arguments:
var multiply = (x, y) => x * y;
(arg1, …, argn) => { statements }
(arg1, …, argn) => single_expression

30
VARIABLE SCOPE

• In JavaScript there are three types of scope:


– Global scope
– Function scope
– Block scope (since ES2015)

31
GLOBAL SCOPE

• Variables that are defined outside of any function or


block are in GLOBAL Scope.
• All scripts and functions on a web page can access it.

• Automatically turn a variable to global


– If you assign a value to a variable that has not been
declared, it will automatically become
a GLOBAL variable.
– We can avoid this by setting our script to "strict mode".
• This system responds to this situation by throwing a
ReferenceError.
• Put this statement: 'use strict'; before any other statements in
your script or the function.
32
FUNCTION (LOCAL) SCOPE

• Variables declared within a function (by var or let) have the FUNCTION scope.

• Function arguments also work in 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

var x = 10; var x = 10;


// Here x is 10 // Here x is 10
{ {
var x = 2; let x = 2;
// Here x is 2 // Here x is 2
} }
// Here x is 2 // Here x is 10 34
CONST

• Constants are block-scoped, much like variables defined using the let statement.

• The value of a constant can't be changed through reassignment, and it can't be


redeclared.

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.

• Lexical environment / scope


– This describes how a parser resolves variable names.
– Nested functions have access to variables declared in their outer scope.
– It uses the location where a variable is declared within the source code to determine where
that variable is available, i.e., within scope.

• 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

• In JavaScript, most things are objects.


– From core JavaScript features like strings and arrays to the browser APIs built on top of JavaScript.

• Inside the object, we find:


– A collection of properties, each of which has a name and a value.
• Property names are strings.
• The value can be pretty much anything: strings, numbers, arrays, functions, & objects.

– So we can say that objects map strings to values.

• 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

• As an object is made up of multiple members, we can create an object by literally


writing out the object contents.
var person = { var person = {};
name: {first: 'Henry', last: 'Lee'}, [Link] = {first: 'Henry', last: 'Lee'};
age: 32, [Link] = 32;
gender: 'male', [Link] = 'male';
interests: ['music', 'skiing'], [Link] = ['music', 'skiing'];
greeting: function() { [Link] = function() {
alert('Hi! I\'m ' + [Link] + '.'); alert('Hi! I\'m ' + [Link] + '.');
} };
};

• An object like this is referred to as an object literal.

• 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.

• In an event, this refers to the element that received the event.

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.

function Person (first, last, age, gender, interests) {


[Link] = {
'first': first,
'last': last
};
[Link] = age;
[Link] = gender;
[Link] = interests;
[Link] = function() {
alert('Hi! I\'m' + [Link] + '.');
};
}

var man = new Person('Henry','Lee', 32, 'male', ['music', 'skiing']); 41


C R E AT E A N O B J E C T

• 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.

function Person (first, last, age, gender, interests) {


:
:
}

var man = new Person('Henry','Lee', 32, 'male', ['music', 'skiing’]);

var boy = [Link](man);


[Link]([Link]); // => 32
[Link]([Link]); // => Henry

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]

• Another way to access object properties is to use bracket notation.

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

• We can add new properties to an object during runtime.

man['eyes'] = 'hazel';
[Link] = function() { alert("Bye everybody!"); }

44
DESTRUCTURING ASSIGNMENT
STAT E M E N T

• This assignment expression makes it possible to unpack values from arrays, or


properties from objects, into distinct variables

• Array destructuring let arr = ['one', 'two', 'three', 'four', 'five'];


const [first, second] = arr;
const [start, , , ,end] = arr;
const [p, q, ...x] = arr;
[Link](first); //- 'one'
[Link](second); //- 'two'
[Link](end); //- 'five'
• Object destructuring [Link](x); //- ['three','four','five']

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

• Destructing assignment (Arrays and Objects)


const [first, ...rest] = [1, 2, 3, 4]; // first = 1, rest = [2, 3, 4]
const {a, ...others} = { a: 1, b: 2, c: 3 }; // a = 1, others = { b: 2, c: 3 }

• 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];

arr1 = [...arr1, ...arr2]; // arr1 becomes [0, 1, 2, 3, 4, 5]

46
S P R E A D SY N TA X ( … A B C )

• Copying and merging objects


const obj1 = { foo: "bar", x: 42 };
const clonedObj = { ...obj1 }; // { foo: "bar", x: 42 }

const obj2 = { bar: "baz", y: 13 };

const mergedObj = { ...obj1, ...obj2 }; // { foo: "bar", x: 42, bar: "baz", y: 13 }

– Overriding object properties when copying and merging

const objA = { foo: "bar", x: 42 };


const objB = { foo: "baz", y: 13 };

const mergedObj = { x: 41, ...objA, ...objB, y: 9 }; // { x: 42, foo: "baz", y: 9 }

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/catch/finally statement marks a block of code to try and specifies a


response should an exception be caught.
– It handles some or all of the errors that may occur in a block of code

• The try statement allows you to define a block of code to be tested for errors while
it is being executed.

• The catch statement allows you to define a block of code to be executed, if an


error occurs in the try block.

• 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

• JavaScript Import statement is used to import bindings that are exported by


another JavaScript module.
– A JavaScript module is a file that encapsulates JavaScript code to be reused across
different files.
– To make objects, functions, classes or variables available of the module, it’s as simple as
exporting them and then importing them where needed in other files.

• A feature under ES2015 (ES6).

52
EXPORTING

Default export (only one per module)


• export default expression;
• export default function fname(…) { … }
• export { nameX as default };

Named exports (any number)


• export function fname() { … }
• export var nameJ = … ;
• export { nameA, nameB, nameC, … };
• export { nameX as otherX, nameY as otherY, …};
53
[Link]

IMPORTING

Import the default of a module


• import nameX from '[Link]';
• you can give it a name of your choice
Import all exports of a module
• import * as extM from '[Link]';
• [Link]();
Import with alias
• import { fname as myfunc } from '[Link]';

Import
• import { nameX, nameY } from '[Link]';
54
[Link]
DAT E A N D T I M E

• The Date object is used to work with dates and times


– Date objects encapsulate an integral number that represents milliseconds since the midnight
at the beginning of January 1, 1970, UTC (the epoch)

• Date objects are created with new Date().

• [Link]() – returns a number that represents the number of milliseconds elapsed


since January 1, 1970 00:00:00 UTC

• 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

• They are built-in JavaScript functions

• setInterval( ) timeID = setInterval(function, milliseconds, param1, param2, ...)


– Repeat calling a function at specified intervals (in units of millisecond)
– [optional] param1, param2, … are parameters to pass to the function
– To stop, call clearInterval(timeID)

• setTimeout( ) timeID = setTimeout(function, milliseconds, param1, param2, ...)

– Set a timer which executes a function once the timer expires


– To cancel, call clearTimeout(timeID)

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.

• According to the W3C, the DOM is a:


– Platform- and language-neutral interface that will allow programs and scripts to dynamically
access and update the content, structure and style of documents.

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>

document is called a node.


– Nodes are connected, so the whole
document can be represented as a tree.

• The DOM is a collection of nodes:


– element nodes,
– text nodes, and
– attribute nodes.

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

• Nodes have a number of available 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:

[Link]([Link]); // => "COMP3322 Test Page"

63
DOCUMENT OBJECT

• Some essential document object properties and methods


Properties / Method Description
doctype Returns the Document Type Declaration associated with the document.
forms Returns a collection of all <form> elements in the document.
head Returns the <head> element of the document.
title Sets or gets the title of the current document.
createAttribute() Creates an attribute node
createElement() Creates an element node
createTextNode() Create a text node
getElementById() Returns the element node whose id attribute matches the parameter.
getElementsByClassName() Returns a NodeList containing all elements with the specified class name.
getElementsByTagName() Returns a NodeList containing all elements with the specified tag name.
querySelector() Returns the first Element node within the document that matches the specified
selectors.
querySelectorAll() Returns all the Element nodes within the document that match the specified
selectors.
write() Writes HTML expressions or JavaScript code to a document. 64
ACCESSING ELEMENT NODES
var elm = [Link]("header");
var elm = [Link]("#header");
<!doctype html> var elm = [Link]("h1");
<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>

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');

var elm = [Link]("moodle");


66
ELEMENT NODE OBJECT

• The type of object returned by the method [Link]() is an element


node object.
– This represents an HTML element in the hierarchy, contains everything between the opening
<> and closing </> tags for this element.
– Can itself contain more elements.

• Element objects implement the DOM Element interface, which has its own set of
properties and methods.

67
[Link]

ELEMENT NODE OBJECT

• Some essential element object properties and methods


Property / Method Description
attributes Returns a collection of this element node's attributes.
className Sets or returns the value of the class attribute of this element.
id Sets or returns the value of the id attribute of this element.
innerHTML Sets or returns the markup content of this element.
style Sets or returns the value of the style attribute of an element (if is a HTMLElement).
tagName Returns the tag name of an element.
nextElementSibling Returns the immediately following Element sibling node or null if none
prevElementSibling Returns the immediately previous Element sibling node or null if none
addEventListener() Attaches an event handler to this element.
getAttribute() Returns / sets / removes the specified attribute value of this element.
setAttribute()
removeAttribute()

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;

var Alnk = [Link]("a")[0].getAttribute('href');


69
ADDING CONTENT
[Link]

<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>

var elm = [Link]('p').innerHTML;


[Link]('p').innerHTML =
elm + "<p> My phone no. is: 2859 7073 </p>"

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

• Placing <script> before the elements


– E.g., at <head> block or immediately below <body> tag

<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>

What is the output?


[Link]

< S C R I P T > TAG – D E F E R AT T R I B U T E

• 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

• Events are actions or occurrences that happen in the system.

• When system detects an event, it fires a signal of some kind/form and some action can
be automatically taken to handle the event.

• In the case of the Web, there are many types of events:


– The user is clicking the mouse over a certain element.
– The cursor is hovering over an element.
– The user is pressing a key on the keyboard.
– The user is resizing or closing the browser window.
– A web page is loaded completely.
– An error occurred.

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

Attribute Event Description


onclick click The mouse clicks an element.
ondblclick dblclick Double-click on an element.
onmousedown mousedown A mouse button is pressed down on an element.

onmousemove mousemove The mouse pointer is moving while it is over an


element.
onmouseout mouseout The mouse pointer moves out of an element.
onmouseover mouseover The mouse pointer moves over an element.

onmouseup mouseup A mouse button is released over an element.

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.

• Keyboard events Attribute Event Description


onkeypress keypress When a user presses a key. (Deprecated)
onkeydown keydown When a user is pressing a key.
onkeyup keyup When a user releases a key.

To get more information on HTML events, please visit: [Link]


80
REGISTERING EVENT HANDLERS

• 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

• You can specify the function to be run in an attribute in the markup.

<button onclick="alert('Hello, this is my old-fashioned event handler!');">


Press me</button>

• They are considered bad practice.


– It is not a good idea to mix up your HTML and your JavaScript, as it becomes hard to parse.
– Could lead to a maintenance nightmare.

[Link]

82
[Link]
AS A METHOD

• We can keep the code strictly within the <script>.

<button id="bttn">Press me</button>


<script>
var bttn = [Link]("bttn");
[Link] = function() {
alert('Hello, this is my old-fashioned event handler!’);
};
</script>

• 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()

<button id="bttn">Press me</button>


<script>
var bttn = [Link]("bttn");
function bttnClick () {
alert('Hello, this is my old-fashioned event handler!’);
};
[Link]('click', bttnClick);
</script>

• Inside the addEventListener() function, we specify two parameters:


– the name of the event, e.g, click
– the code of the handler function

• 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()

• We can remove event handler code using removeEventListener()

• Same as addEventListener(), we specify two parameters:


– the name of the event
– the handler function

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

• When an event is fired on an element:


– The browser first checks whether that element has an event handler for that event, and runs it if
so.
– Afterwards, it checks the next immediate ancestor element and does the same thing, then the
next ancestor, and so on until it reaches the <html> element.

• In that case, one user action can trigger multiple event handlers in action.

• This is the default behavior of modern browsers.

• The exact opposite behavior is called Capturing.

87
[Link]

E V E N T P R O PAG AT I O N – C A P T U R I N G

• The browser checks to see if the onclicked element's outer-most ancestor


(<html>) has an onclick event handler registered for capturing, and runs it if so.

• 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.

• To use the Capturing behavior, we set the third argument of the


addEventListener() to true, which is set to false by default.
[Link](event, function, useCapture)
addEventListener('click', bgChange, true)

88
[Link]
EVENT OBJECT

• Some essential properties and methods of the event object

Property / Method Description


bubbles Indicates whether the event bubbles property is enable.
cancelable Returns a Boolean value indicating whether or not an event is a cancelable event. The
event is cancelable if it is possible to prevent the events default action to be
happened.
currentTarget Refers to the element to which the current event handler is attached to, as opposed to
target which identifies the element on which the event occurred.
defaultPrevented Returns whether or not the preventDefault() method was called for the event.
target Returns the element that triggered the event.
type Returns the name of the event.
preventDefault() Instructs the system to cancel the default action if the event is cancelable.
stopPropagation() Prevents further propagation of an event during event propagation.

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

• Exceed the maximum length. minlength maxlength

• The number is too large or small. min max


• The input is not a valid email address or URL.

• The input does not match the required pattern. pattern

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.

• When an element XX is valid:


– This matches the XX:valid styling rule, the system will apply the specific style to that valid
element XX.

• When an element XX is invalid:


– This matches the XX:invalid styling rule and the specific style will be applied.
– The browser will block the form from submission and display an error message.

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

• HTML5 provides another API called constraint validation.

• The purpose is for us to check the state of a form element; given the state, we can take
appropriate actions.

• It’s also possible to change the text of the error message.

98
[Link]

C O N ST R A I N T VA L I DAT I O N A P I

Property / Method Description


validity A ValidityState object describing the validity state of the
element.
[Link] Set to true, if an element's value does not match its pattern
attribute.
[Link] Set to true, if an element's value is greater than its max attribute.
[Link] Set to true, if an element's value is less than its min attribute.
[Link] Set to true, if an element's value exceeds its maxLength
attribute.
[Link] Set to true, if an element (with a required attribute) has no value.
checkValidity() Returns true if an input element contains valid data.
setCustomValidity() Adds a custom error message to the element

99
[Link]

When user enters


E
JavaScript
X A M P L E something to the
input element
<script>
var email = [Link]("email");
[Link]("input", function (event) {
if ([Link]) {
[Link]([Link]);
[Link]("Enter a valid email address");
} else {
[Link]("");
}
});

var snum = [Link]("number");


[Link]("input", function (event) {
if ([Link]) {
[Link]([Link]);
[Link]("Must be 10 digits starts with 3015");
} else {
[Link]("");
}
});
</script>
EXAMPLE
JavaScript
<script>
var email = [Link]("email");
[Link]("input", function (event) {
if ([Link]) {
[Link]([Link]);
[Link]("Enter a valid email address");
} else { This function checks
[Link](""); whether the value matches
}
the specific pattern
});

var snum = [Link]("number");


[Link]("input", function (event) {
if ([Link]) {
[Link]([Link]);
[Link]("Must be 10 digits starts with 3015");
} else {
[Link]("");
}
});
READINGS

• MDN Web Docs


– JavaScript First Steps
• [Link]

– JavaScript Building Blocks


• [Link]

– Manipulating Documents
• [Link]
side_web_APIs/Manipulating_documents

102
REFERENCES

• Some slides are borrowed from the book:


– Fundamentals of Web Development by Randy Connolly and Ricardo Hoar, published by
Pearson.

• [Link]
– JavaScript Tutorial
• [Link]

• JavaScript Info
– [Link]

103

You might also like