server services,
e.g., MySQL/MariaDB
|
dynamic content/presentation:
PHP
|
webserver:
e.g., Apache
HTML, CSS, JavaScript
/\
|
\/
client:
web-browser
dynamic content/presentation:
JavaScript
|
client:
web-browser
content:
HTML
presentation:
CSS

js-1 JS Fundamental

JavaScript is often used for web pages as a client-side programming language, but it is also used as a server-side programming language.

js-1.1 JS for web page

  1. HTML to define the content of web pages
  2. CSS to specify the layout of web pages
  3. JavaScript to program the behavior of web pages

Reference JavaScript Tutorial at:
https://www.w3schools.com/js/default.asp

Return to JavaScript menu

js-1.2 head, body, external

JS codes and additional JS codes may be

  1. placed in head section, and/or
  2. placed in body section, and/or
  3. placed in external JS files and referenced in head section, and/or
  4. placed in external JS files and referenced in body section
  5. placed as event handler attribute

js-1.2.1 head, body

HTML tag: <script>
content of HTML element: <script> JS codes </script>
In body section and/or head section:

<html>
  <head>
    <script>
    JS codes in head section
    </script>
  </head>
  <body>
    <script>
    JS codes in body section
    </script>
  </body>
</html>

Return to JavaScript menu

js-1.2.2 external

External JS files:
ScriptFileName1.js
ScriptFileName2.js
Reference in head or body in HTML file:

<html>
  <head>
    <script src=fileName1.js> </script>
    <script>
    JS codes in head section
    </script>
  </head>
  <body>
    <script src=fileName2.js> </script>
    <script>
    JS codes in body section
    </script>
  </body>
</html>

Reference Where to at:
https://www.w3schools.com/js/js_whereto.asp

Return to JavaScript menu

js-1.2.3 event handler

HTML event examples:
HTML web page has finished loading
HTML input field is changed
HTML button is clicked

Syntax:
element event = "JS codes"

Example:
<div id="js010203Demo">Date and time:</div>
<button type="button" onclick='document.getElementById("js010203Demo").innerHTML = Date()'>Click Me</button>

Date and time:

Reference JS Events at:
https://www.w3schools.com/js/js_events.asp

Return to JavaScript menu

js-1.3 Examples with html/css

Examples of what JS can do to html and/or css are:

Reference JavaScript Introduction at:
https://www.w3schools.com/js/js_intro.asp

js-1.3.1 Change element content

Example:
<div id="js010301Demo">Question/Answer</div>
<button type="button" onclick='document.getElementById("js010301Demo").innerHTML = "Who is there?"'>clickForQuestion</button><br>
<button type="button" onclick='document.getElementById("js010301Demo").innerHTML = "Me"'>clickToAnswer</button>

produces:

Question/Answer

Return to JavaScript menu

js-1.3.2 Change attribute value

Example:
<img id="js010302Image" src="../images/logo-caritas.jpg" style="width:50px"><br>
<button onclick='document.getElementById("js010302Image").src= "../images/logo-cihe.svg"'>clickForCIHE</button><br>
<button onclick='document.getElementById("js010302Image").src= "../images/logo-caritas.jpg"'> clickForCaritas</button>

produces:



Return to JavaScript menu

js-1.3.3 Change property value

Example:
<p id="js010303Demo">p initial font</p>
<button type="button" onclick='document.getElementById("js010303Demo").style.fontSize= "larger"'>click to change to larger fontSize</button><br>
<button type="button" onclick='document.getElementById("js010303Demo").style.fontSize= "small"'>click to change to small fontSize</button>

produces:

p initial font


Return to JavaScript menu

js-1.3.4 Hide/Show content

Example:
<p id="js010304Demo">HTML element content </p>
<button type="button" onclick='document.getElementById("js010304Demo").style.display= "none"'>click to Hide</button><br>
<button type="button" onclick='document.getElementById("js010304Demo").style.display= "block"'>click to Show</button>

produces:

HTML element content


Return to JavaScript menu

js-1.3.5 exercise

Create a webpage to display a picture, with a button to change to a large size of the picture and another button to restore to the smaller size.

Return to JavaScript menu

js-2 Output to:

JavaScript can write to:

Reference Output at:
https://www.w3schools.com/js/js_output.asp

Return to JavaScript menu

js-2.1 innerHTML

Example:
<div id="js-0201-demo">Who is there?</div>
<button type="button" onclick='document.getElementById("js-0201-demo").innerHTML = "Me"'> clickToAnswer</button><br>
<button type="button" onclick='document.getElementById("js-0201-demo").innerHTML = "Who is there?"'> clickForQuestion</button>

produces:

Who is there?

Return to JavaScript menu

js-2.2 document.write()

Example to overwrite the entire document of parent element:
<script>
document.write("name" + 1 + 4)
</script>

producrs:

<script>
document.write("name" + "<br>" + 1 + 4)
</script>

producrs:

Return to JavaScript menu

js-2.3 window.alert()

Example to overwrite the entire document of parent element:
<script>
window.alert("name" + 1 + 4);
</script>

Return to JavaScript menu

js-2.4 console.log()

Example to overwrite the entire document of parent element:
<script>
console.log(1 + 4);
</script>

Return to JavaScript menu

js-3. Syntax

js is case-sensitive

Reference Syntax
https://www.w3schools.com/js/js_syntax.asp

js-3.1 comment

// comment in single line
codes // comment appended in single line
/* comment in single line */
/* comment in
multiple lines */

Example:
<p id="js0301Demo">Original</p>
<!-- HTML comment: assign an id to the HTML element p -->
<script>
var x; // JS comment: declare variable x
x = 2; // JS comment: assign value to x
document.getElementById("js0301Demo").innerHTML = x;
/* child of document is the HTML element with id="js0301Demo" */
/* child of the HTML element is the content
with reserved name: innerHTML
assign value of x to it */
/* the HTML element content is now this newly assigned value */
</script>

Original

Read and practice Comments at:
https://www.w3schools.com/js/js_comments.asp

Return to JavaScript menu

js-3.2 fixed value: number

number:
<p id="js0302Demo">Original</p>
<script>
document.getElementById("js0302Demo").innerHTML = 3.14;
</script>

Original

Read and practice numbers at:
https://www.w3schools.com/js/js_numbers.asp

Return to JavaScript menu

js-3.3 fixed value: string

string:
<p id="js0303Demo"></p>
<script>
document.getElementById("js0303Demo").innerHTML = 'Last Name';
</script>

Original

Read and practice Strings at:
https://www.w3schools.com/js/js_strings.asp

Return to JavaScript menu

js-3.4 var lat const (variable value)

Scope Declare Declare, Assign Assign -> declare Reassign Redeclare
var Global var x; var x; x = 1;
or
var x = 1;
or
x = 1;
x = 1; var x = 1;
x = 2;
var x = 1;
x = "1";
let Block {let x;} {let x; x = 1;}
or
{let x = 1;}
{x = 1;
let x;}
Syntax error
{let x = 1;
x = 2;}
{let x = 1;
x = "1";}
Syntax error
const Block {const x;} {const x; x = 1;}
or
{const x = 1;}
{x = 1;
const x;}
Syntax error
{const x = 1;
x = 2;}
Syntax error
{const x = 1;
x = "1";}
Syntax error

js-3.4.1 declare variable, assign value:

Example:
<p id="js0304Demo">Original</p>
<script>
var x0304; //declare variable
x0304 = 3.14; //assign
document.getElementById("js0304Demo").innerHTML = x0304;
</script>

Original

js-3.4.2 declare and assign:

Example:
<p id="js03041Demo">Original</p>
<script>
var x1 = 5; //declare variable and assign value
document.getElementById("js03041Demo").innerHTML = x1;
</script>

Original

js-3.4.3 declare multiple variables

Example
<p id="js03042Demo">Original</p>
<script>
var pi, radius; //declare multiple variables
pi = 3.14; //assign
radius = 1; //assign
document.getElementById("js03042Demo").innerHTML = 2 * pi * radius;
</script>

Original

js-3.4.4 declare multiple variables and assign

Example
<p id="js03043Demo">Original</p>
<script>
var pi = 3.14, radius = 1, diam; //declare and assign
diam = radius * 2; //assign
document.getElementById("js03043Demo").innerHTML = pi * diam;
</script>

Original

Read and practice Variables at:
https://www.w3schools.com/js/js_variables.asp

Return to JavaScript menu

js-3.5 arithmetic operators

+ // add
- // subtract
* // multiple
/ // divide
** // exponentiation
% // modulo
++ // increment
-- // decrement
<p id="js03051Demo">Original</p>
<script>
document.getElementById("js03051Demo").innerHTML = (3 + 2 - 1) * 5 / 2;
</script>

Original

<p id="js03052Demo">Original</p>
<script>
var x = 1, y = 4;
x++; y--;
document.getElementById("js03052Demo").innerHTML = x * y;
</script>

Original

<p id="js03053Demo">Original</p>
<script>
var x = 1, y = 4;
x++; y--;
document.getElementById("js03053Demo").innerHTML = x ** y % 5;
</script>

Original

Read and practice Operators at:
https://www.w3schools.com/js/js_operators.asp

Return to JavaScript menu

js-3.6 expression

(Math) expression computes/evaluates to a (number or string) value from values, variables with operators.

expression:
<p id="js0306Demo">Original</p>
<script>
var x = 3;
var y = x - 1;
y = y + 3;
document.getElementById("js0306Demo").innerHTML = y * x - 5;
</script>

Original

expression:
<p id="js03061Demo">Original</p>
<script>
document.getElementById("js03061Demo").innerHTML = "data" + "base";
</script>

Original

expression:
<p id="js03062Demo">Original</p>
<script>
document.getElementById("js03062Demo").innerHTML = "family " + "name";
</script>

Original

Return to JavaScript menu

js-3.7 assign

x = y;
x += y; // is same as x = x + y;
x -= y; // is same as x = x - y;
x *= y; // is same as x = x * y;
x /= y; // is same as x = x / y;
x %= y; // is same as x = x % y;

Reference Assignment
https://www.w3schools.com/js/js_assignment.asp

Return to JavaScript menu

js-3.8 identifier

is name of variable, keyword, function, label:
1st character must be: letter or _ or $

JS is case sensitive

Customary in JS to join multiple words into an identifier using
lower Camel Case: myStyle, lastName, airTicket
and not my-style, last-name, etc. because Hyphen is reserved for subtraction

Return to JavaScript menu

js-3.9 statement

JavaScript program/code is a list of programming statements/instructions, separated by ; (semicolon). The ; at the end of the statement is recommended, though not mandatory.

Spaces are added merely to improve readability.

The best place to break is after an operator.

A group of JS statements may be grouped in a code block inside { ... } to be executed together such as in a JS function.

Reference statement
https://www.w3schools.com/js/js_statements.asp

Return to JavaScript menu

js-3.10 keywords

Some keywords are: break - terminates a switch or a loop
continue - jumps out of a loop and starts at the top
debugger - stops execution and calls the debugger function
do ... while
for
function - declares a function
if ... else
return
switch
try ... catch - implements error handling to a block of statements
var

Return to JavaScript menu

js-4 Data

Data types:

Primitive data: the primitive data value is a single simple data value with no additional properties and methods.

Complex data:

Object types:

Return to JavaScript menu

js-4.1 typeof

typeof operator returns the type of a variable or an expression

Example:
<p id="js04011Demo">Original</p>
<script>
var js04011variable = true;
var js04012variable = undefined;
var js04013variable;
var js04014variable = { width:"12px", color:"green" };
function js04015function(js04015) { js04015 + 1 };
document.getElementById("js04011Demo").innerHTML =
typeof 42 + "<br>" +
typeof "dignity of the human person" + "<br>" +
typeof "" + "<br>" +
//empty string
"js04011variable is of type: " + typeof js04011variable "<br>" +
"js04012variable is of type: " + typeof js04012variable "<br>" +
"js04013variable is of type: " + typeof js04013variable "<br>" +
"js04014variable is of type: " + typeof js04014variable "<br>" +
"js04015function is of type: " + typeof js04015function;
</script>

Original

Reference data types
https://www.w3schools.com/js/js_datatypes.asp

Return to JavaScript menu

js-4.2 String

A JavaScript string is zero or more characters written inside quotes. It is used for storing and manipulating text.

'string inside single quote'
"string inside double quote"
are the same

Example:
<p id="js04022Demo">Original</p>
<script>
document.getElementById("js04022Demo").innerHTML = 'break ' +
"a long string"

Original

'use "double quote" inside a string inside single quote' or
"use 'single quote' inside a string inside double quote"

Backslash (\) escape character turns special a character into a string character.

'The \' is interpreted as a character "'" in this string'

\' is '
\" is "
\\ is \

Example:
<p id="js04021Demo">Original</p>
<script>
document.getElementById("js04021Demo").innerHTML =
'break after an \'operator\''
</script>

Original

Reference string
https://www.w3schools.com/js/js_strings.asp

Return to JavaScript menu

js-4.2.1 String methods

JavaScript treats primitive values as objects when executing methods and properties

length property

<p id="js0402011Demo">Original</p>
<script>
var txt="caring for the weakest of the weak";
document.getElementById("js0402011Demo").innerHTML = txt.length

Original

indexOf() method returns the position of the first occurrence of the string; position is an optional parameter to count from it if provided.

<p id="js0402012Demo">Original</p>
<script>
var txt="caring for the weakest of the weak";
document.getElementById("js0402012Demo").innerHTML = txt.indexOf("weak");

Original

lastIndexOf("string",position) method returns the position of the last occurrence of the string; position is an optional parameter to count up to it if provided.

<p id="js0402013Demo">Original</p>
<script>
var txt="caring for the weakest of the weak";
document.getElementById("js0402013Demo").innerHTML = txt.lastIndexOf("weak");

Original

Reference string methods
https://www.w3schools.com/js/js_string_methods.asp

Return to JavaScript menu

js-4.3 Number

JavaScript has the only one type of number: 64-bit floating point.

0123456789012345678901234567890123456789012345678901234567890123
(bit 0-51 -----------------------------------------)(bit 52-62)
Mantissa............................................Exponent...s
------------------------------------------- bit 63 is sign bit:s

Example
let x = 20; // digit
let x = 3.14; // with decimals
let x = 3e8; // +ve exponent (speed of light in meters per second)
let x = 6.674e-11; // -ve exponent (gravitational constant)

JavaScript uses the + operator for:
addition with 2 numbers, concatenation with 2 strings, or
concatenation with 1 string and 1 number (convert the number to string first).

JavaScript interpreter works from left to right

Example (here the first + is addition, whereas the later + is concatenation):
<p id="js04031Demo">Original</p>
<script>
x = 12;
y = 8;
z = "22";
document.getElementById("js04031Demo").innerHTML = x + y + z
</script>

Original

JavaScript will try to convert string to number in numeric (but not concatenation) operation.

Example
<p id="js04032Demo">Original</p>
<p id="js04033Demo">Original</p>
<script>
x = "12";
y = "3";
z = "2";
document.getElementById("js04032Demo").innerHTML = x / y - z +
" // convert to number for division and minus"
document.getElementById("js04033Demo").innerHTML = x / y - z + x +
" // concatenate for + with string"
</script>

Original

Original

Reference Numbers
https://www.w3schools.com/js/js_numbers.asp

Return to JavaScript menu

js-4.4 Boolean

Boolean() function of an expression (or a variable) takes the value of true or false.

Comparison operators
== is equal to
> is greater than
< is less than

<button onclick="js0404Function()">Click</button> <p id="js0404Demo">Original</p>
<script>
function js0404Function() {
document.getElementById("js0404Demo").innerHTML=Boolean(0.5 == 1/2);
}
</script>

original

Reference Boolean
https://www.w3schools.com/js/js_booleans.asp

Return to JavaScript menu

js-4.5 Function

function functionName(parameter1, parameter2, ..., parameter 5) {
//code to be executed
}

functionName(parameter1, parameter2, ..., parameter 5) is the function value

Example:
<p id="js04051Demo">Original</p>
<script>
document.getElementById("js04051Demo").innerHTML = js04051Function(1, 2, 3)
function js04051Function(a, b, c) {
return a + b * c;
}
</script>

Original

functionName is the function object

Example:
<p id="js04052Demo">Original</p>
<script>
document.getElementById("js04052Demo").innerHTML = js04052Function
function js04052Function(a, b, c) {
return a + b * c;
}
</script>

Original

Reference Function
https://www.w3schools.com/js/js_functions.asp

Return to JavaScript menu

js-4.5.1 exercise (Project 6c)

This project use JavaScript to validate a form input.

Create a form using HTML for a user to input one's age. On submitting the form, the age is checked such that it must be a positive number and must not exceed 120.

Enter you age:

Check that the age is not over 120

Reference JS Forms
https://www.w3schools.com/js/js_validation.asp

Return to JavaScript menu

js-4.6 Object

A JavaScript object is a variable, and is a container for one or more named values, which are properties or methods

A method is a function stored as a property

Example:
var objectName = { propertyName1: propertyValue1, propertyName2: propertyValue2, ..., propertyName4: propertyValue4 };

objectProperty is propertyName: propertyValue pair

A property is accessed
objectName.propertyName
or
objectName["propertyName"]

Example:
<p id="js04061Demo">Original</p>
<p id="js04062Demo">Original</p>
<script>
var course = {
name: "web and HCI development",
duration: "15 weeks",
credits: 3,
contactHours: 45,
studyHours: 90,
totalHours: function() { return this.contactHours + this.studyHours }
};
document.getElementById("js04061Demo").innerHTML = course.duration;
document.getElementById("js04062Demo").innerHTML = course.totalHours();
</script>

js04061Demo

js04062Demo

Reference Object
https://www.w3schools.com/js/js_objects.asp

Return to JavaScript menu

js-4.7 array

An array variable can hold multiple values at the same time.

Syntax:
var array_name = [ item1, item2, ... ];

Same as (but avoid using)
var array_name = new Array(item1, item2, ... );

elements of array
var array_name[0] = item1
array_name[1] = item2

<p id="js04071Demo">Original</p>
<p id="js04072Demo">Original</p>
<script>
var family = [ "father", "mother", "child" ];
document.getElementById("js04071Demo").innerHTML = family;
document.getElementById("js04072Demo").innerHTML = family[0]
</script>

Original

Original

Reference array
https://www.w3schools.com/js/js_arrays.asp

Return to JavaScript menu

js-6 HTML DOM

The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.

HTML DOM Tree of Objects

Upon loading a web page, the browser creates a DOM Tree of Objects of the page, e.g.:

                ------------
               |  document  |
                ------------
                     |
                ------------
               |root element|
               |    html    |
                ------------ 
                     |
     ----------------------------------
    |                                  |
 -------                            -------
|element|                          |element|
| head  |                          | body  |
 -------                            -------
    |                                  |
    |                             ----------
    |                            |          |
 -------         ---------    -------    -------    ---------    --------
|element|       |attribute|__|element|  |element|__|attribute|__|property|
| title |       |  href   |  |   a   |  |  div  |  |  style  |  |  font  |
 -------         ---------    -------    -------    ---------    --------
    |                            |          |
 -------                      -------    -------
| text  |                    | text  |  | text  |                         
|       |                    |       |  |       |                         
 -------                      -------    -------
	
	

The HTML DOM defines:
each HTML element as an object,
and the events for all HTML elements,
where the programming interface for each object are
the properties (values to get or set) of the HTML element, and
the methods (actions) to access the HTML element

It is a standard for how to get, change, add, or remove HTML elements.

JS can add, remove, change HTML elements and attributes, change the (css) styles (properties), and react to or create events.

Reference JS HTML Dom
https://www.w3schools.com/js/js_htmldom.asp

Return to JavaScript menu

js-6.1 HTML DOM Document

The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.

Finding HTML Elements Method:
document.getElementById("id")
document.getElementsByTagName("name")
document.getElementsByClassName("name")

Changing HTML Elements property:
element.innerHTML = new content // change content of element
element.attribute = new value // change attribute value of element
element.style.property = new style // change style property value of element

Changing HTML Elements Method:
element.style.setAttribute(attribute, value) // change attribute value of element

Adding/Deleting Elements Method:
document.createElement(element) // create an element
document.removeChild(element) // remove an element
document.appendChild(element) // add and element
document.replaceChild(new, old) // replace and element
document.write(text) // write to html output stream

Adding Events Handlers:
document.getElementById(id).onclick = function() {code} // add event handler code to an onclick event

Finding HTML Objects property
document.anchors // all <a> elements that have a name attribute
document.baseURI // absolute base URI of document
document.body // <body> element
document.cookie // document's cookie
document.doctype // document's doctype
document.documentElement // <html> element
document.documentMode // mode used by browser
document.documentURI // URI of the document
document.domain // domain name of document server
document.embeds // all <embed> elements
document.forms // all <form> elements
document.head // <head> element
document.images // all <img> elements
document.implementation // the DOM implementation
document.inputEncoding // document's encoding (character set)
document.lastModified // date and time document was updated
document.links // all <areat> and <a> elements that have a href attribute
document.readyState // loading status
document.referrer // URI of the referrer
document.scripts // all <script> elements
document.strictErrorChecking // whether error checking is enforced
document.title // <title> element
document.URL // complet URL of document

Reference JS HTML DOM Document
https://www.w3schools.com/js/js_htmldom_document.asp

Return to JavaScript menu

js-6.2 access HTML Elements

js-6.2.1 getElementById

Finding HTML Elements by ID:
document.getElementById("id")

Example
<p id="js06021Source">content from p with id="js06021Source"</p>
<p id="js06022Destination">p with id="js06022Destination"</p>
<script>
var js06021Demo = document.getElementById("js06021Source");
document.getElementById("js06022Destination").innerHTML = "copied " + js06021Demo.innerHTML;
</script>

content from p with id="js06021Source"

p with id="js06022Destination"

js-6.2.2 getElementsByTagName

Finding HTML Elements by tag name:
document.getElementsByTagName("name")

Example
<h6>0th heading 6 content</h6>
<h6>1st heading 6 content</h6>
<p id="js06023Demo">destination</p>
<script>
var js06023TagName = document.getElementsByTagName("h6");
document.getElementById("js06023Demo").innerHTML = "copied " + js06023TagName[0].innerHTML;
</script>

0th heading 6 content
1st heading 6 content

destination

Finding HTML child Elements by tag name inside an HTML parent element:

Example
<div id="js06024Demo">
<p>0th paragraph content</p>
<p>1st paragraph content</p>
</div>
<p id="js06025Demo">destination</p>
<script>
var js06024Id = document.getElementById("js06024Demo");
var js06025TagName = js06024Id.getElementsByTagName("p");
document.getElementById("js06025Demo").innerHTML = '1st paragraph inside "js06024Demo" is: ' + js06025TagName[1].innerHTML;
</script>

0th paragraph content

1st paragraph content

destination

js-6.2.3 getElementsByClassName

Finding HTML Elements by class name:
document.getElementsByClassName("name")

Example
<h3 class="js060261Demo">0th element content</h3>
<p class="js060261Demo">1st element content</p>
<p id="js060262Demo">destination</p>
<script>
var js06026ClassName = document.getElementsByClassName("js060261Demo");
document.getElementById("js060262Demo").innerHTML = '0th element with class "js060261Demo" is: ' + js06026ClassName[0].innerHTML;
</script>

0th element content

1st element content

destination

js-6.2.4 querySelectorAll

Finding HTML Elements by querying CSS selector,
i.e. to find all HTML elements that match a specified CSS selector (id, class, names, types, attributes, values of attributes, etc.):
document.querySelectorAll("selector")

Example
<p class="js060271Demo">0th paragraph content</p>
<p class="js060271Demo">1st paragraph content</p>
<p id="js060272Demo">destination</p>
<script>
var js06027Selector = document.querySelectorAll("p.js060271Demo");
document.getElementById("js060272Demo").innerHTML = '0th paragraph with selector "p.js060271Demo" is: ' + js06027Selector[0].innerHTML;
</script>

0th paragraph content

1st paragraph content

destination

js-6.2.5 forms

Finding HTML Elements by HTML Object Collections:
document.forms("formId")

Example
<form id="js06028formId" action="/action_page.php">
Name: <input type="text" name="fname" value="King"><br>
Email: <input type="email" name="email" value="abc@gmail.com"><br><br>
<input type="submit" value="Submit">
</form>
<button onclick="js06028Function()">Click to display form values</button>
<p id="js06028Demo"></p>
<script>
function js06028Function() {
var js06028Var = document.forms["js06028formId"];
var js06028Content = "";
var i;
for (i = 0; i < js06028Var.length ;i++) {
js06028Content += js06028Var.elements[i].value + "
";
}
document.getElementById("js06028Demo").innerHTML = js06028Content;
}
</script>

Name:
Email:

Reference JS HTML DOM Element
https://www.w3schools.com/js/js_htmldom_elements.asp

Return to JavaScript menu

js-6.3 HTML content

Create dynamic HTML output


<script>
document.write(Date());
</script>

HTML content


<p id="js06031Demo">original content in p with id="js06031Demo"</p>
<script>
var js06031Date = new Date();
document.getElementById("js06031Demo").innerHTML = 'change content of p with id="js06031Demo" to day of the week is: ' + js06031Date.getDay();
</script>

original content in p with id="js06031Demo"

Reference Changing HTML
https://www.w3schools.com/js/js_htmldom_html.asp

Return to JavaScript menu

js-6.4 attribute value

Change attribute (e.g., href, id, src, width, height, class) content:

Syntax:
document.getElementById(id).attribute = new value of the attribute

change image

Example
<p>change original picture: <img src = "../images/logo-cihe.svg"> to</p>
<img id="js06041Demo" src="../images/logo-cihe.svg">
<script>
document.getElementById("js06041Demo").src = "../images/logo-caritas.jpg";
</script>

change original picture: to

change image size

Example
<p>change picture size: <img src = "../images/logo-cihe.svg" width="200"> to</p>
<img id="js06042Demo" src="../images/logo-cihe.svg" width="200">
<script>
document.getElementById("js06042Demo").width = "400";
</script>

change picture size: to

Reference Changing HTML
https://www.w3schools.com/js/js_htmldom_html.asp

Return to JavaScript menu

js-6.4.1 removeAttribute

Remove attribute (e.g., href, id, src, width, height, class) content:

Syntax:
document.getElementById(id).removeAttribute = attribute

Example
<a href="https://cis.cihe.edu.hk" id="js060401Demo">School of Computing and Information Sciences</a><br>
<button type="button"
onclick='document.getElementById("js060401Demo").removeAttribute("href")'>Click to remove hyperlink</button><br>
<button type="button"
onclick='document.getElementById("js060401Demo").href="https://cis.cihe.edu.hk"'>restore hyperlink</button>

School of Computing and Information Sciences

Reference remove Attribute
https://www.w3schools.com/jsref/met_element_removeattribute.asp

Return to JavaScript menu

js-6.5 CSS style property

Change style property value:

Syntax:
document.getElementById(id).style.property = new value

N.B. style property in JS becomes fontSize, fontFamily, backgroundColor, etc. for these same property in CSS: font-size, font-family, background-color, etc.
(hyphen is reserved for subtraction)


<p class="right">Original: <a href="#js-00"> Return to JavaScript menu</a></p>
<p class="right">Change to: <a id="js06051Demo" href="#js-00"> Return to JavaScript menu</a></p>
<script>
document.getElementById("js06051Demo").style.color = "red";
document.getElementById("js06051Demo").style.backgroundColor = "yellow";
document.getElementById("js06051Demo").style.fontFamily = "courier";
document.getElementById("js06051Demo").style.fontSize = "larger";
</script>

Original: Return to JavaScript menu

Change to: Return to JavaScript menu

<p id="js06052Demo">p default font</p>
<button type="button" onclick='document.getElementById("js06052Demo").style.fontSize= "larger"'>click to larger fontSize</button><br>
<button type="button" onclick='document.getElementById("js06052Demo").style.fontSize= "small"'>click to small fontSize</button><br>
<button type="button" onclick='document.getElementById("js06052Demo").style.color= "red"'>click to turn red</button><br>
<button type="button" onclick='document.getElementById("js06052Demo").style.color= "blue"'>click to turn blue</button><br>
<button type="button" onclick='document.getElementById("js06052Demo").style.display= "none"'>click to Hide</button><br>
<button type="button" onclick='document.getElementById("js06052Demo").style.display= "block"'>click to Show</button><br>

p font






Reference Changing CSS
https://www.w3schools.com/js/js_htmldom_css.asp

Return to JavaScript menu

js-6.5.1 classList

Syntax:
element.classList

add, remove, toggle, length, contains, item

document.getElementById("Id").classList.length; // # of class attributes of the element
document.getElementById("Id").classList.contains("className"); // True if it contains, False otherwise
document.getElementById("Id").classList.item(i); // className of the ith class (starts at 0)
document.getElementById("Id").classList.add("className1,className2"); // add classes to the element
document.getElementById("Id").classList.remove("className1,className2"); // remove classes from the element
document.getElementById("Id").classList.toggle("className"); // remove classes from the element

Example
<p id="js060501Demo"><a href="#js-00">Return to JavaScript menu</a></p>
<button type="button" onclick='document.getElementById("js060501Demo").classList.add("right")'>Align to right</button><br>
<button type="button" onclick='document.getElementById("js060501Demo").classList.remove("right")'>remove alignment</button><br>
<button type="button" onclick='document.getElementById("js060501Demo").classList.toggle("right")'>toggle alignment</button><br>

Return to JavaScript menu




Reference classList
https://www.w3schools.com/jsref/prop_element_classlist.asp

Return to JavaScript menu

js-6.5.2 className

Syntax:
element.className // returns the className property
element.className = class // sets className property
element.className = class1 class2 ... // sets className property

return the className

Example
<p id="js060502Id" class="right"><a href="#js-00">Return to JavaScript menu</a></p>
<button type="button" onclick="js060502Function()">return className</button>
<p id="js060502Demo"></p>
<script>
function js060502Function() {
var js060502Name = document.getElementById("js060502Id").className;
document.getElementById("js060502Demo").innerHTML = js060502Name;
}
</script>

Return to JavaScript menu

set the className

Example
<div id="js0605021Demo"><a href="#js-00">Return to JavaScript menu</a></div>
<button type="button" onclick="js0605021Function()">set className</button>
<script>
function js0605021Function() {
document.getElementById("js0605021Demo").className = "right";
}
</script>

overwrite the className

Example
<div id="js0605022Demo" class="right"><a href="#js-00">Return to JavaScript menu</a></div>
<button type="button" onclick="js0605022Function()">set className</button>
<script>
function js0605022Function() {
document.getElementById("js0605022Demo").className = "center-title";
}
</script>

Reference className
https://www.w3schools.com/jsref/prop_html_classname.asp

Return to JavaScript menu

js-6.6 event

JS codes added to an HTML event attribute are executed upon the event.

Example HTML events:

  1. mouse clicks
  2. web page has loaded
  3. image has loaded
  4. mouse over/touch an element
  5. change an input field
  6. submit an HTML form
  7. strike a key

Reference Events
https://www.w3schools.com/js/js_htmldom_events.asp

Return to JavaScript menu

js-6.6.1 change element content

Change content of an html element upon an event

<h3 onclick='this.innerHTML = "dignity of the human person"'>click me</h3>

click me

Return to JavaScript menu

js-6.6.2 event handler to execute function

Execute a function to change content of an html element from an event handler

<h3 onclick="js0606021Function(this)" style="background-color:yellow;">click me</h3>
<script>
function js0606021Function(js0606021Element) { js0606021Element.innerHTML = "dignity of the human person"; }
</script>

click me

Assign event to an html element using event attribute

<h3 onclick="js0606022Function()">click me</h3>
<p id="js0606022Demo">day of the month</p>
<script>
var js0606022Date = new Date();
function js0606022Function() { document.getElementById("js0606022Demo").innerHTML = js0606022Date.getDate(); }
</script>

click me

day of the month

Return to JavaScript menu

js-6.6.3 Assign event - DOM

Assign event to an html element in HTML DOM

Assign event to HTML element:

<button id="js0606031Button">click me</button>
<p id="js0606031Demo">month</p>
<script>
document.getElementById("js0606031Button").onclick = js0606031Function;
var js0606031Date = new Date();
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
function js0606031Function() { document.getElementById("js0606031Demo").innerHTML = months[js0606031Date.getMonth()]; }
</script>


month

Return to JavaScript menu

js-6.6.4 onload

onload event: when entering the web page

Check Cookie when entering the web page:

<html>
<body onload="checkCookies()">
<p id="js0606041Demo">checkCookie</p>
<script>
function checkCookies() {
var js0606041Cookie = " ";
if (navigator.js0606041Cookie == true)
{js0606041Cookie = "Cookies are enabled.";}
else {js0606041Cookie = "Cookies are not enabled.";}
document.getElementById("js0606041Demo").innerHTML = js0606041Cookie;
}
</script>
</body>
</html>



checkCookie

Return to JavaScript menu

js-6.6.5 onchange

Syntax:
<element onchange="JS code"> /* in HTML
object.onchange = function(){JS code}; /* in JS
object.addEventListener("change", JS code); /* in JS using addEventListener() method

onchange is often used in combination with validation of input field

Execute toUpperCase() when user leaves input entry field:


Enter family name: <input id="js0606051Demo" onchange="js0606051Function()" type="text">
<script>
function js0606051Function() {
var x = document.getElementById("js0606051Demo");
x.value = x.value.toUpperCase();
}
</script>


Enter family name:


<p>Vincent Lebbe 雷鳴遠格言:</p>
<p id="js0606052Lebbe"> </p>
<select id="js0606052Select" onchange="js0606052Function()">
<option value="sacrifice">全犧牲</option>
<option value="love">真愛人</option>
<option value="joy" selected="selected">常喜樂</option>
<option value="(Please select)"></option>
</select>
means <span id="js0606052Demo"> </span>
<script>
function js0606052Function() {
var js0606052Chinese = document.getElementById("js0606052Select").innerHTML;
var js0606052English = document.getElementById("js0606052Select").value;
document.getElementById("js0606052Lebbe").innerHTML = js0606052Chinese;
document.getElementById("js0606052Demo").innerHTML = js0606052English;
}
</script>


Vincent Lebbe 雷鳴遠格言:

means

Reference onchange
https://www.w3schools.com/jsref/event_onchange.asp

Return to JavaScript menu

js-6.6.6 onmouseover and onmouseout

onmouseover and onmouseout: change color


<h2 onmouseover="style.color='red'" onmouseout="style.color='blue'" style="background-color:pink;width:350px;height:20px;">mouseover demo</h2>


mouseover demo

onmouseover and onmouseout: change text


<div onmouseover="js0606061Over(this)" onmouseout="js0606061Out(this)" style="background-color:pink;width:200px;height:20px;"> is Mouse Out</div>
<script>
function js0606061Over(obj) {obj.innerHTML = "is Mouse Over"}
function js0606061Out(obj) {obj.innerHTML = "is Mouse Out"}
</script>


is Mouse Out

Reference onmouseuover
https://www.w3schools.com/jsref/event_onmouseover.asp

Reference onmouseout
https://www.w3schools.com/jsref/event_onmouseout.asp

Return to JavaScript menu

js-6.6.7 onmousedown and onmouseup

onmousedown and onmouseup: change text


<div onmousedown="js0606071Down(this)" onmouseup="js0606071Up(this)" style="background-color:pink;width:200px;height:20px;">Hold mouse click</div>
<script>
function js0606071Down(obj) {
obj.style.backgroundColor = "blue";
obj.innerHTML = "Release mouse click";
}
function js0606071Up(obj) {
obj.style.backgroundColor="pink";
obj.innerHTML="Hold mouse click";
}
</script>


Hold mouse click

onmousedown and onmouseup: change image


<img id="js0606072Image" onmousedown="js0606072On()" onmouseup="js0606072Off()" src="../images/logo-caritas.jpg">
<script>
function js0606072On() {
document.getElementById('js0606072Image').src = "../images/logo-cihe.svg";
}
function js0606072Off() {
document.getElementById('js0606072Image').src = "../images/logo-caritas.jpg";
}
</script>


Reference onmousedown
https://www.w3schools.com/jsref/event_onmousedown.asp

Reference onmouseup
https://www.w3schools.com/jsref/event_onmouseup.asp

Return to JavaScript menu

js-6.6.8 onfocus and onblur


Enter last name: <input onfocus="js060608Focus(this)" id="js060608Id" onblur="js060608Blur()" type="text">
<script>
function js060608Focus(x) {
x.style.background = "yellow";
}
function js060608Blur() {
var x = document.getElementById("js060608Id");
x.value = x.value.toUpperCase();
x.style.background = "white";
}
</script>


Enter last name:

Reference onfocus
https://www.w3schools.com/jsref/event_onfocus.asp

Reference onblur
https://www.w3schools.com/jsref/event_onblur.asp

Return to JavaScript menu

js-6.7 EventListener

addEventListener() method attaches an event handler to an element without overwriting existing event handlers

Syntax:
element.addEventListener(event, function, useCapture);

event examples are "click", "mousedown" etc. and NOT "onclick", "onmousedown"

useCapture is optional and is default to false (bubbling)

Return to JavaScript menu

6.7.1 function in addEventListener parameter


<button id="js060701Id">please click</button>
<script>
document.getElementById("js060701Id").addEventListener("click", function() { alert("clicked");});
</script>


Return to JavaScript menu

6.7.2 external function


<button id="js060702Id">please click</button>
<script>
document.getElementById("js060702Id").addEventListener("click", js060702Function);
function js060702Function() { alert("clicked"); }
</script>


Return to JavaScript menu

6.7.3 multiple event handlers


<button id="js060703Id">click, mouseover, mouseout</button>
<p id="js060703Demo">user actions are:<br></p>
<script>
var js060703element = document.getElementById("js060703Id")
js060703element.addEventListener("mouseover", js060703mouseover);
js060703element.addEventListener("mouseout", js060703mouseout);
js060703element.addEventListener("click", js0607031click);
js060703element.addEventListener("click", js0607032click);
function js060703mouseover() {
document.getElementById("js060703Demo").innerHTML += "moused over
";
}
function js060703mouseout() {
document.getElementById("js060703Demo").innerHTML += "moused out
";
}
function js0607031click() {
document.getElementById("js060703Demo").innerHTML += "clicked
";
}
function js0607032click() {
alert("clicked");
}
</script>


user actions are:


Return to JavaScript menu

6.7.4 for window object


<p id="js060704Demo"> </p>
<script>
window.addEventListener("resize", function(){
document.getElementById("js060704Demo").innerHTML = Math.random();
});
</script>



Return to JavaScript menu

6.7.5 parameter


<button id="js060705Id">click</button>
<p id="js060705Demo"> </p>
<script>
var p1 = 3;
var p2 = 5;
document.getElementById("js060705Id").addEventListener("click", function(){
js060705Function(p1, p2);
});
function js060705Function(a, b) {
document.getElementById("js060705Demo").innerHTML = a + b;
}
</script>



Return to JavaScript menu

6.7.6 bubble or capture

Syntax:
element.addEventListener(event, function, useCapture);

Bubble: order of executing event from that of inner element to outter element:
element.addEventListener(event, function, false);
or
element.addEventListener(event, function);

Capture: order of executing event from that of outter element to inner element:
element.addEventListener(event, function, true);

Example with p (inner) element inside div (outter) element:

<div id="js0607061Bubble" style="background-color:grey;width:300px;margin:auto;border:dashed black 10px">
<p id="js0607062Bubble" style="background-color:yellow; width:200px; margin:10px auto;"> Click bubble events</p>
</div>
<div id="js0607061Capture" style="background-color:grey;width:300px;margin:auto;border:dashed black 10px">
<p id="js0607062Capture" style="background-color:yellow; width:200px; margin:10px auto;"> Click Capture events</p>
</div>
<script>
document.getElementById("js0607062Bubble").addEventListener("click", function() {
alert("Clicked the inner area");}, false);
document.getElementById("js0607061Bubble").addEventListener("click", function() {
alert("Clicked the outter area");}, false);
document.getElementById("js0607062Capture").addEventListener("click", function() {
alert("Clicked the inner area");}, true);
document.getElementById("js0607061Capture").addEventListener("click", function() {
alert("Clicked the outter area");}, true);
</script>


Click bubble events

Click Capture events


Return to JavaScript menu

6.7.7 removeEventListener


<div id="js060707Area" style="background-color:grey;width:300px;margin:auto;border:dashed black 10px">
<p id="js060707add" style="background-color:yellow; width:200px; margin:10px auto;">onmousemove event displays a random number</p>
<button onclick="js060707remove()">Stop</button>
</div>
<script>
document.getElementById("js060707Area").addEventListener("mousemove", js060707Function);
function js060707Function() {
document.getElementById("js060707add").innerHTML = Math.random();
}
function js060707remove() {
document.getElementById("js060707Area").removeEventListener("mousemove", js060707Function);
}
</script>


onmousemove event displays a random number


Reference EventListener
https://www.w3schools.com/js/js_htmldom_eventlistener.asp

Return to JavaScript menu