Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
49 views

Lab 9: Javascript Web1201: Web Fundamentals: Rev 1.6.5 November, 2020

This document provides an introduction to JavaScript and how it differs from server-side languages like PHP. It explains that JavaScript can be used to make web pages more interactive by adding logic and processing on the client-side browser. The document outlines some of JavaScript's capabilities, such as manipulating HTML and responding to user events, as well as its limitations compared to server-side languages. It also distinguishes between in-browser JavaScript, which can interact with web pages, and non-browser JavaScript like Node.js, which is used for server-side functions.

Uploaded by

阿符的故事
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Lab 9: Javascript Web1201: Web Fundamentals: Rev 1.6.5 November, 2020

This document provides an introduction to JavaScript and how it differs from server-side languages like PHP. It explains that JavaScript can be used to make web pages more interactive by adding logic and processing on the client-side browser. The document outlines some of JavaScript's capabilities, such as manipulating HTML and responding to user events, as well as its limitations compared to server-side languages. It also distinguishes between in-browser JavaScript, which can interact with web pages, and non-browser JavaScript like Node.js, which is used for server-side functions.

Uploaded by

阿符的故事
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Rev 1.6.

5
November, 2020

Lab 9: JavaScript
WEB1201: Web Fundamentals

1 Introduction
This lab aims to help you learn how to include JavaScript into your HTML file to make them
more interactive for the user. In previous labs, we would have looked at how you could add
some logic but processed on the server side using PHP. In this lab, you will see how you can
add logic on the client side using JavaScript. This means the scripts are processed on the user’s
machine allowing the scripts to be more responsive.

2 Objectives
At the end of this lab, you should be able to:

1. Add JavaScript to your web pages.


2. Include JavaScript to forms and use them for input checks.

3 Pre-requisites
Before you attempt this lab, it is important that you have completed earlier labs on HTML, CSS,
Page Layouts, Forms and PHP (for some programming basics). You are expected to understand
at least the following topics:

1. HTML terminology: elements, tags, attributes.


2. CSS terminology and knowing how to apply CSS in a variety of ways.
3. The Box Model: understanding padding, margins, etc. and how to apply them.
4. Page layouts: be able to apply a style to your page and form.
5. Forms: be able to create a form with the relevant inputs and be able to style them.
6. PHP: More importantly the programming basics from this.

Note

For this lab, you will required to know some basic programming, including the understand-
ing of variables, functions, etc. If you need refreshing on this, please consult any additional
lab sheets or your instructor.

1
4 Deliverables, timing and additional notes
The estimated time of completion for this lab is approximately four hours. This does not include
the time you will need to answer the questions. You are to compile your work after every lab -
this includes all codes (and comments where necessary), documentation, completed tasks and
answered questions. You will need to submit the work you have produced in this lab.

5 Materials and Equipment


1. A computer with a web browser and text editor (VS Code preferred)
NOTE:
If you are using the computers in the lab, you will need to use a portable browser which
is available from eLearn.

Note

1. Have a logbook to write down notes for labs. This will help you revise and reflect on
the work you have done in the lab. The lab is not intended as a typing exercise but
one that requires you to reflect and think about what you have done and learnt.
2. For this lab, you will need to use the browser’s Inspector. If you are doing this in the
lab, you will need to use a portable browser for this.

6 Recap
We have processed data input from forms using PHP (PHP: Hypertext Preprocessor) which is
a server-side scripting language. What this means is that the execution of the script happens
on the server and not on the client. A script is a plain text program that does not need special
preparation or compilation to run. The plain text script is interpreted by the Zend Engine (i.e.
an open source PHP engine). What happens is the engine reads (“parses”) the script, converts
(“compiles”) the script to the machine language and the machine runs the code. This is pretty
much how many scripting languages run. There are other languages that require compiling and
building source code to an executable file before you run it.

In this lab, you will be discovering another scripting language: JavaScript.

7 What is JavaScript?
Despite what the name may suggest, JavaScript has nothing to do with Java (a programming
language). Like PHP, it is a scripting language but it is typically executed using a virtual ma-

2
chine in the browser1 . This means, PHP is code that is executed by the server (and the user
has no control over it) and JavaScript is executed by the client (and the user can choose to
turn JavaScript processing off). This is why the main difference (that is often stated) between
PHP and JavaScript is that PHP is a server-side scripting language and JavaScript a client-side
scripting language.

However, as long as you have an interpreter (i.e. a JavaScript engine), it can run on any machine
with or without the browser. One example is to use Node.js (which includes the V8 JavaScript
engine) to run JavaScript on the computer rather than only within a web browser. The ability to
run JavaScript on the computer allows JavaScript to be used as a server-side language as well.

There are many different JavaScript engines with different codenames:

1. V8 - in Chrome and Opera.


2. SpiderMonkey - in Firefox.
3. Trident, Chakra - in IE
4. ChakraCore - in Edge
5. Nitro and SquirrelFish - in Safari

There are a few things that makes JavaScript a choice for web developers:

1. Full integration with HTML/CSS.


2. Simple things are done simply.
3. Support by all major browsers and enabled by default2 .

8 In-browser vs Non-in-browser JavaScript


Here, we are going to differentiate the two:

1. in-browser JavaScript
Able to do everything related to webpage manipulation, interaction with the user, and the
webserver. For example:
(a) Add new HTML to the page, change the existing content, modify styles.
(b) React to user actions, run on mouse clicks, pointer movements, key presses.
(c) Send requests over the network to remote servers, download and upload files (so-
called AJAX and COMET technologies).
(d) Get and set cookies, ask questions to the visitor, show messages.
(e) Remember the data on the client-side (“local storage”).
1
This is called “in-browser JavaScript” and we will differentiate this later on.
2
Recall that it can be disabled by the user

3
Note: You can also use cookies and sessions to store data on the client and retrieve
them using PHP superglobals $_COOKIE, $_SESSION.
2. non-browser based JavaScript (primarily Node.js)
Focused on server side functions, e.g. create a HTTP server, write to console, etc.

8.1 Can in-browser JavaScript really do everything?

Recall that the statement says it is able to do everything related to webpage manipulation, in-
teraction with the user and the webserver. Basically, only things related to the webpage. This
restriction is by design as a safety feature - otherwise, anyone on the Internet can run malicious
code on your computer to do harm.

Here are some things in-browser JavaScript cannot do:

1. JavaScript on a webpage may not read/write arbitrary files on the hard disk, copy them or
execute programs. It has no direct access to OS system functions.
Modern browsers allow it to work with files, but the access is limited and only provided
if the user does certain actions, like “dropping” a file into a browser window or selecting
it via an <input> tag. (e.g. uploading your files via eLearn)
There are ways to interact with camera/microphone and other devices, but they require a
user’s explicit permission. So a JavaScript-enabled page may not sneakily enable a web-
camera, observe the surroundings and send the information to a malicious website or an
attacker.
2. Different tabs/windows generally do not know about each other. Sometimes they do, for
example when one window uses JavaScript to open the other one. But even in this case,
JavaScript from one page may not access the other if they come from different sites (from
a different domain, protocol or port (see the note for “What is a port?”)).
This is called the “Same Origin Policy”. To work around that, both pages must agree for
data exchange and contain a special JavaScript code that handles it. This limitation is,
again, for the user’s safety. A page from http://anysite.com which a user has opened
must not be able to access another browser tab with the URL http://gmail.com and
steal information from there.
3. JavaScript can easily communicate over the net to the server where the current page came
from. But its ability to receive data from other sites/domains is crippled. Though possible,
it requires explicit agreement (expressed in HTTP headers) from the remote side. Once
again, that’s a safety limitation.

4
Note

What is a port?
A port is a logical endpoint of an application. For instance, when you started your XAMPP
Control, there is a column for ports and these represent the ports the applications are bound
to. Not all applications on your computer need to be bound to a port. Only when they want
network access - which can either be:

1. outgoing (i.e. the application wants to send data out)


e.g. when you send a HTTP request using your web browser
2. incoming (i.e. the applications wants to wait for incoming data by creating a listening
sockets which are bound to port numbers)
e.g. when you start your Apache Web server, it creates listening sockets on port 80
(for HTTP requests) and 443 (for HTTPs requests)

These ports have numbers so that the computer will know which application you are trying
to communicate with (as there can be multiple applications running on the computer at any
one time). Thus, when you want HTTP service, the browser requests it from port 80 and
the computer will know that the browser wants to communicate with the HTTP server. Port
numbers are a 16-bit value. To see the ports used on your Windows computer:

1. Launch a “Command Prompt” (just do a search or press Windows Key + R and


type in “cmd”)
2. Run the commands:
• netstat -an
• netstat

Question(s) 1

These are questions that are designed to help you better understand the underlying nature
of how network and communications between computers work.

1. What is the theoretical maximum number of ports given that it is a 16-bit value?
2. Explain the different states in the “STATE” column of the output of the netstat com-
mand.
3. Run netstat /? to get a list of commands. Based on the list of commands, determine
what the earlier command netstat -an does?
4. Create the command that shows the Fully Qualified Domain Name.

5
9 My first JavaScript
In the previous labs, you were introduced to PHP, which is a server-side scripting language.
JavaScript (JS) is a scripting language3 (just like PHP) which can be written right in a web
page’s HTML and run automatically as the page loads (yes you can combine PHP and HTML
in the same file). One of the main differences is that PHP is considered a server-side only
language.

A summary of your main learning points are as follows:

1. Learning how to add Javascript to a HTML file that will run in your web browser.
You will be trying two methods of adding the JavaScript code:
(a) within the HTML file (Task 1), and
(b) by linking the script to the HTML file (Task 2).
2. You will have to read through and understand the DOM - and more specifically the HTML
DOM. From this, you will:
(a) Learn how to read (get) and write (set) HTML values using different methods (Task 3).
(b) Learn how to trigger a script to run rather than just making it run when the page
loads. You will learn how to do this using on-event triggers and addEventLis-
tener(). (Task 4).
3. Learn how to run JavaScript not within a browser, i.e. using node.js. (Task 7).
4. Learn how to use JavaScript to perform form validation. (Task 8).

Note

If you encounter problems with your JavaScript, open Opening the Web Console in
your Web Console to be able to see the output and Firefox Developer Edition.
where the error it is occurring at. To open your Web
Console:
• Ctrl+Shift+K in Firefox Developer edition, or
• Ctrl+Shift+I to bring up the Inspector in Google
Chrome then look at the “Console”)

You will be testing out the use of the Web Console by


deliberately introducing an error in Step 6 of Task 1.

3
Scripts are provided and executed as plain text. They don’t need special preparation or compilation to run.

6
Task 1: Embedding JavaScript in a HTML file
In this task, you are going to learn how to add in JavaScript to your HTML file and observe the
order of execution of the scripts. To embed JavaScript code in a HTML document, it needs to
be contained, or encapsulated, in a script element. The JavaScript is typed between the opening
<script> tag and the closing </script> tag.
1 <script> // The start of a script
2 JavaScript statement goes here;
3 Each line ends with a semicolon (like in PHP);
4 </script>

As web pages are rendered by the browser from top to bottom it means our scripts will execute
wherever they are located in the document. Let us examine this using this example:

1. Create the file first_script.html4 with these <body> contents.


1 <body>
2 <p>Before the script...</p>
3
4 <script> // Start of the JS script
5 alert(’Hello, world!’);
6 </script>
7
8 <p>...After the script.</p>
9 </body>

2. Record what do you notice about the order of execution of the script.
3. To your HTML file, add in:
• another alert message box script after the last paragraph (i.e. after the last <p>). Call
this “Message Box 2” to differentiate it from the first.
• another paragraph with the text “...after the second alert box”.
What do you notice about the order of execution now?
4. You can repeat the addition process to different parts of your document to test this prop-
erty of execution from top to bottom.
5. What did you notice about the number of occurrences of an alert box or pop-up window?
What can you conclude from this observation?
6. In this step, you are going to deliberately introduce an error into your script. Add an “a”
before “alert” to become “aalert”. Use your Web Console to detect the error.
4
You will still have to save the file as a HTML file. Scripts will be detected between the <script> tags and
will be executed when encountered.

7
Question(s) 2

1. Describe the order of execution of JavaScript.


2. How many times are your scripts executed? Explain what triggers the execution
of the scripts you have written so far.

Task 2: Linking JavaScript in a HTML file


Another option for including a JavaScript on a page is to create the script in an external text
file and save it with a .js extension (making it a JavaScript file). The .js file is then included
in the page using the src attribute of the opening script tag. Note: The process of putting the
JavaScript in an external file is similar to what you would do for external CSS.

1. Create a .js file. Save this file as: myscript.js


2. Place this JavaScript code (without the script tags) into the .js file.
1 // This is a function that will create a pop-up in your browser.
2 alert( ’Hello, world!’ );

3. Create another HTML file: external_js.html with the basic HTML page template.
4. Add the JavaScript script in the <body> of your HTML file.
1 <script src="myscript.js"></script>

5. Record your observation.

Question(s) 3

1. Describe when you will use an external JavaScript file.


2. Describe the differences between adding an external JS file (using relative
links) and:
(a) an external JavaScript file using an absolute link to:
i. local file
ii. a remote file located on a server
Note: Not a Dropbox, OneDrive, etc. shared link but a file that can be
directly linked, e.g. http://somedomain.com/somefolder/somejsfile.js
(b) an external CSS file
(c) an image (local to the server) within a <div>
3. Explain if you can add the following files from an external HTTP server using
relative links:

8
(a) CSS file
(b) JavaScript file
(c) image file
(d) a binary file intended for users to download

9.1 JavaScript async and defer

So far, we have seen scripts (e.g. in “first_script.html”) being evaluated “in-order” of the writing
of the document but this is not always the case. Sometimes, when you have long scripts (which
is getting more common), it may take a long time for your HTML to appear.

The async and defer attributes are boolean attributes that indicate how the script should be
evaluated. Classic scripts may specify defer or async, but must not specify either unless the src
attribute is present. Module scripts may specify the async attribute, but must not specify the
defer attribute.

For classic scripts, if the async attribute is present, then the classic script will be fetched in
parallel to parsing and evaluated as soon as it is available (potentially before parsing completes).
If the async attribute is not present but the defer attribute is present, then the classic script will
be fetched in parallel and evaluated when the page has finished parsing. If neither attribute is
present, then the script is fetched and evaluated immediately, blocking parsing until these are
both complete.

For module scripts5 , if the async attribute is present, then the module script and all its depen-
dencies will be fetched in parallel to parsing, and the module script will be evaluated as soon
as it is available (potentially before parsing completes). Otherwise, the module script and its
dependencies will be fetched in parallel to parsing and evaluated when the page has finished
parsing. (The defer attribute has no effect on module scripts.)

This is easiest understood as a figure shown in Figure 1.

So far, you have only created alerts and its use seem limited (more of an annoyance really). To
be able to harness what JS can do, you need to be able to detect in a web page and with some
logic, make changes (i.e. manipulate) to that page. What you will be detecting and changing
will be the basic building block of a HTML page: the elements. Now, how will you then
determine which elements you want to detect or change? This is where the DOM comes in.

5
Think of a module script as a collection of functions that perform a certain function or operation, e.g. authen-
ticating a user

9
Scripting:
<script>
HTML Parser:
Scripting:
<script defer>
HTML Parser:
Scripting:
<script async>
HTML Parser:
Scripting:
<script type=”module”>
HTML Parser:
Scripting:
<script type=”module” async>
HTML Parser:

parser fetch execution runtime

Figure 1: Visualization of how async and defer affects script loading and execution. Redrawn
from here.

10 DOM: Document Object Model


The DOM is a W3C (World Wide Web Consortium) standard that defines a standard for access-
ing documents: “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, struc-
ture, and style of a document.”

The W3C DOM standard is separated into 3 different parts:

1. Core DOM - standard model for all document types


2. XML DOM - standard model for XML documents
3. HTML DOM - standard model for HTML documents

The Document Object Model (DOM) is the data representation of the objects that comprise
the structure and content of a document on the web. The Document Object Model (DOM) is a
programming interface for HTML and XML documents. It represents the page so that programs
can change the document structure, style, and content. The DOM represents the document as
nodes and objects. That way, programming languages can connect to the page. Remember, this
is the general description of what a DOM is.

10.1 The HTML DOM

Every web page resides inside a browser window which can be considered as an object. A Web
page is a document. This document can be either displayed in the browser window or as the
HTML source. But it is the same document in both cases. The Document Object Model (DOM)
represents that same document so it can be manipulated. The DOM is an object-oriented repre-
sentation of the web page, which can be modified with a scripting language such as JavaScript.

10
The HTML DOM is created by the browser when a web page is loaded. The HTML DOM
model is constructed as a tree of Objects. An example of this tree of Objects for this code:
1 <html> // Level 1
2 <head> // Level 2
3 <title>My title</title> // Level 3
4 </head>
5
6 <body> // Level 2
7 <h1>Header 1</h1> // Level 3
8 <p id="">Text</p> // Level 3
9 <script src="myscript.js" async></script>
10 </body>
11 </html>

is shown in Figure 2.

Root element:
Level 1
<html>

Element: Element:
Level 2
<head> <body>

Element: Element: Element: Attribute:


Level 3
<title> <h1> <p> “id”

Text: Text: Text:


“My title” “Header 1” “Text”

Figure 2: Visualization of the HTML DOM tree.

11
10.2 DOM vs HTML

Initial DOM after This tree of objects, or nodes, representing the page’s content is called
HTML loads: the DOM. Right now it looks the same as the HTML, but suppose that
html the script referenced at the bottom of the HTML runs a code that re-
head moves the h1 node and adds another p node to the DOM.:
title
body 1 const h1 = document.querySelector(’h1’);
2 h1.parentElement.removeChild(h1);
h1
3 const p = document.createElement(’p’);
p
4 p.textContent = ’Wildcard!’;
script
5 document.body.appendChild(p);
DOM after
The page’s HTML is now different than its DOM. In other words,
changes by the
HTML represents initial page content, and the DOM represents cur-
script:
rent page content. When JavaScript adds, removes, or edits nodes, the
html
DOM becomes different than the HTML.
head
So far, what you have been looking at in the browser’s inspector is the
title
DOM (although for your codes it has always looked liked the HTML
body
code itself - since your code does not have scripts that will change the
p
page after loading).
script
p

10.3 Nodes

What are these nodes or node objects? Let’s take a look at Figure 2 again. When you look at
this DOM tree, you will notice that some of the items in the tree are labelled as “element” and
some are labelled as “text”. This tells you that not all node objects are elements. In fact, there
are different types of node objects. You can see this in Table 1.

You might have noticed that there are some missing values from the table, e.g. 2, 5, 6, etc. The
missing values from the table are deprecated node types and have been omitted from this table.
You can find those values: here.

12
Table 1: HTML DOM Node types

Constant Value Description


Node.ELEMENT_NODE 1 An Element node like <p> or <div>.
Node.TEXT_NODE 3 The actual Text inside an Element or Attr.
Node.CDATA_SECTION_NODE 4 A CDATASection, such as <!CDATA[[ . . . ]]>.
13

Node.PROCESSING_INSTRUCTION_NODE 7 A ProcessingInstruction node of an XML document, such as <?xml-stylesheet . . . ?>.


Node.COMMENT_NODE 8 A Comment node, such as <!– . . . –>.
Node.DOCUMENT_NODE 9 A Document node.
Node.DOCUMENT_TYPE_NODE 10 A DocumentType node, such as <!DOCTYPE html>.
Node.DOCUMENT_FRAGMENT_NODE 11 A DocumentFragment node.
10.4 How can I think of the DOM?

A Web page is a document. This document can be either displayed in the browser window
or as the HTML source. But it is the same document in both cases. The Document Object
Model (DOM) represents that same document so it can be manipulated. The DOM is an object-
oriented representation of the web page, which can be modified with a scripting language such
as JavaScript.

Note

If you are familiar with Object-Oriented Programming (OOP) terminology, a lot of what is
going to be said here is based on that. If you aren’t, it is a good idea to get familiarized with
the concepts of OOP, such as:

1. objects
2. properties
3. methods (or functions/actions)

Discussion of these concepts is beyond the scope of this lab sheet or subject and it is ex-
pected that the student will read up on their own.

10.4.1 HTML elements as objects

When using the DOM, the browser window, web page document, and any HTML element
are considered to be objects. The browser window is an object. When a web page loads in
the browser, the web page is considered to be a document. The document itself is an object.
The document can contain objects such as images, headings, paragraphs, and individual form
elements such as text boxes.

10.4.2 Object Properties

The objects may have properties that can be detected or manipulated. For example, a property
of the document is its title. Another property of the document is its background colour.

10.4.3 Object Methods

There are actions that can be performed on some objects. For example, the window object can
display the alert message box or a prompt box. This type of action is called a method. You
can create your own methods if you create your own objects (which is beyond the scope of this
document as the primary focus is on using the existing document or HTML objects).

14
10.5 What can I do with JavaScript and the DOM?

With the object model, JavaScript is able to do (on a page):

1. change, remove, add HTML elements, attributes and CSS


2. react to all existing HTML events
3. create new HTML events

by accessing the properties and methods of each object.

Note

The terms properties and methods are specific terms used in Object-Oriented Programming.

1. HTML DOM methods are actions you can perform (on HTML Elements).
2. HTML DOM properties are values (of HTML Elements) that you can set or
change.

For example, the standard DOM specifies that the getElementsByTagName method in the code
below must return a list of all the <p> elements in the document:
1 var paragraphs = document.getElementsByTagName("p");
2 // paragraphs[0] is the first <p> element
3 // paragraphs[1] is the second <p> element, etc.
4 alert(paragraphs[0].nodeName);

Note:

1. You will see a lot of Object-Oriented Programming jargon used, such as “objects” or
“method(s)”. As the name suggests, just think of objects as a thing or an item (albeit
virtual) and a method as the ability to do something. For example, in the code above,
“document” is the object and “getElementByTagName” is the method that can be per-
formed by this object.
Do you notice that there is another method being called (or “used”) in the sample code?
2. Different objects have different methods. If you are the one creating the blueprint for
creating the object, you can decide what methods your object will have. In our example,
you are merely using what has already been created, i.e. the objects “document” and
“paragraph”.
3. “getElementByTagName” is a type of capitalization used to separate words. It is often
referred to as “CamelCase”. You may come across it often when doing programming,
especially when you are trying to name things.

15
11 Fundamental data types
This reference tries to describe the various objects and types in simple terms. But there are a
number of different data types being passed around the API that you should be aware of and
can be found in Table 2

Table 2: DOM DataTypes

Data type (Inter- Description


face)
Document When a member returns an object of type document (e.g., the own-
erDocument property of an element returns the document to which it
belongs), this object is the root document object itself. The DOM doc-
ument Reference chapter describes the document object.
Node Every object located within a document is a node of some kind. In an
HTML document, each node is an element.
Element The element type is based on node. It refers to an element or a textt-
tnode of type element returned by a member of the DOM API. Rather
than saying, for example, that the document.createElement() method
returns an object reference to a node, we just say that this method re-
turns the element that has just been created in the DOM. element ob-
jects implement the DOM Element interface and also the more basic
Node interface, both of which are included together in this reference.
In an HTML document, elements are further enhanced by the HTML
DOM API’s HTMLElement interface as well as other interfaces de-
scribing capabilities of specific element kinds of elements (for instance,
HTMLTableElement for <table> elements).
NodeList A nodeList is an array of elements, like the kind that is re-
turned by the method document.getElementsByTagName(). Items
in a nodeList are accessed by index in either of two ways:
• list.item(1)
• list[1]
These two are equivalent. In the first, item() is the single method on
the nodeList object. The latter uses the typical array syntax to fetch the
second item in the list.
Attribute When an attribute is returned by a member (e.g., by the createAttribute()
method), it is an object reference that exposes a special (albeit small) in-
terface for attributes. Attributes are nodes in the DOM just like elements
are, though you may rarely use them as such.
NamedNodeMap A namedNodeMap is like an array, but the items are accessed by name
or index, though this latter case is merely a convenience for enumera-
tion, as they are in no particular order in the list. A namedNodeMap
has an item() method for this purpose, and you can also add and remove
items from a namedNodeMap.

16
12 JavaScript language basics
Before we go on and see how JavaScript can be used within our HTML document or web page,
we will first look at some JavaScript basics: some basic functions, variables, loops, conditions,
arrays. We will explore these basics as tasks. Unfortunately, it is not possible to provide some
examples without introducing other concepts of JavaScript. These will be mentioned in the
comments of the examples.

Task 3: Set and Get values


Just like echo in PHP and printf to print formatted output in C, JavaScript has a way of dis-
playing strings on screen. There are mainly four ways to “display” data in JS, the first two by
“setting” values in a HTML element.

1. Writing into an HTML element, using innerHTML.


2. Writing into the HTML output using document.write().
3. Writing into an alert box, using window.alert().

Method 1: Using innerHTML

1. In this step, we will replace the contents of an element by using the innerHTML method.
Read more here.
1 <p id="readme">Something you can read</p>
2 <p id="display"></p>
3
4 <script>
5 document.getElementById("display").innerHTML= "Hello World";
6 // Notice that strings must be enclosed in (double) quotes
7 </script>

Note:
(a) Notice that the we are first selecting a document object. Then the getElementById
method is used to select a particular element. Next, the method innerHTML is used
to replace the contents of the selected element.
Note: The innerHTML method only applies to an element!
(b) In this example, we have used another method: getElementById to select a specific
element to affect.
2. Use the Inspector to look at the <p> element with the id="display". Record your
observation.
3. (Another use of innerHTML: to “get”) Change the code to this:

17
1 <p id="readme">Something you can read</p>
2 <p id="display"></p>
3
4 <script>
5 // Declare a variable
6 var getText;
7 // Assign value to variable. Value is the contents of the element with the
id ‘‘readme’’
8 getText=document.getElementById("readme").innerHTML;
9 // Replace the contents of the element with the id ‘‘display’’
10 document.getElementById("display").innerHTML=getText;
11 </script>

Note:
(a) In this code, the contents of the element with the id “readme” is assigned to the
variable “getText”. See Line 8. This is an assignment of the value to a variable and
it is done using the “=” operator.
(b) Before using a variable, you should first declare it (See Line 6) using the var (to
limit the scope of the variable). Can you use the variable without first the var? Yes.
(c) You can combine Line 6 and Line 8 in one line, i.e.
1 var getText=document.getElementById("readme").innerHTML;

However, when you have multiple variables, performing a declaration and assign-
ment can get messy and splitting them up as was done earlier is preferable.
4. Change Line 2 to include some text in the paragraph element.
What do you notice after the change (if any)? Provide an explanation.
5. Using another method (other than getElementById), change the contents of multiple
elements of the same class. Note:
• You are expected to write your own set of codes (but you can refer to the previous
ones for help).
• Ensure that there are sufficient elements to demonstrate the working of your codes.
• Save the codes for this file as: change_multiple_elements_using_JS.html

Question(s) 4

1. What function does innerHTML perform?


2. How many HTML elements can/should use the same id? Why?

18
Method 2: Using document.write

1. Now try using document.write method.


1 // Example 1: Script invoked DURING initial page load
2 <p>Testing document.write</p>
3
4 <script>
5 document.write("Hello World");
6 </script>

Save the file as: docWrite_example1.html


2. Change the code to:
1 // Example 2: Script invoked AFTER initial page load
2 <p>Testing document.write</p>
3
4 // Create a button to invoke a JavaScript function
5 <button type="button" onclick="document.write(’Hello World’)">Execute
the JS</button>
6 // See Note on single and double quotes

Save the file as: docWrite_example2.html


3. Reload the page and click the button.
4. Use the Inspector to inspect the page. Explain your observation.
Note:
(a) Using document.write overrides all HTML content (you are afterall writing to the
document)
(b) In Example 1, when you first load the page, (recall that) the HTML code is read
line-by-line6 . In this example, the JS is executed during the page load.
(c) In Example 2, the JS is executed after the page has loaded, clearing everything on
the page as it is writing the document itself.
5. Now, we are going to replace the "Hello World" with something more elaborate. It will
still be a string of text. As usual, do not simply copy and paste the code but go through
the code and understand what is happening. In this example, two new concepts are intro-
duced:
• invoking a JS fucntion with the onclick attribute. Read more: click event
• creating a JS function within the script. This function takes no parameters (hence
the empty brackets)
1 // Example 3: A more elaborate document.write
6
We tested the “order of execution” in an earlier lab by demonstrating how elements are nested.

19
2 <p>Testing document.write</p>
3
4 // The button now invokes a JS function
5 <button type="button" onclick="docWrite()">Execute the JS</button>
6
7 <script>
8 // The JS function invoked by the HTML button using the onclick
attribute
9 function docWrite(){
10 // This must be written in a single line as a string, i.e. no line breaks.
11 // Line breaks have been shown here to show you the HTML code you
are entering.
12 document.write("
13 <!DOCTYPE html>
14 <html>
15 <body>
16
17 <h1>Hello World</h1>
18 <p>The whole document content is replaced.</p>
19
20 </body>
21 </html>
22 ");
23 }
24
25 //When the document.write is written in one line it should look like this
26 document.write("<!DOCTYPE html><html><body><h1>Hello World
</h1><p>The whole document content is replaced.</p></body
></html>");
27 </script>

Save the file as: docWrite_example3.html


6. Reload the page and click the button. Use the Inspector to inspect the page. Compare the
code of the page with Example 2 (after clicking the button). Explain your observation.
7. Save all observations in: documentWrite_observations in PDF or docx.

Using Method 1 will result in a XSS vulnerability (because the contents are read as HTML and
a script can be embedded within HTML code). Method 2 will replace the entire contents of the
page. A better method would be to use textContent.

20
Single and double quotes

TL;DR: When declaring a string within another string, you have to use a different
string delimiter.
i.e. if you use double quotes for the outer string, use single quotes for the inner
one and vice versa.

Example (HTML):
onclick="document.write(’Hello World!’)"

You will have noticed the same thing if you tried to declare an SQL SELECT
in PHP which is wrapped in another string to be passed to the mysqli_query
function.

Example (in PHP):


$query="SELECT * FROM user WHERE lastname=’Wong’"

Method 3: Using window.alert()

The alert message box is displayed using the alert() method. We have already seen it being
used in an earlier example.

1. add these lines to a HTML file


1 <script>
2 alert("your message");
3 // This is the same as window.alert("your message");
4 </script>

Note:
(a) JavaScript can be added to a HTML and contained within <script> tags.
Did you notice the two different ways the same message with regards to how the
code can be included in the HTML file was phrased? They mean the same thing. The
reason this is being highlighted is that it doesn’t matter how something is phrased
as long as it conveys the same meaning; and this is true even for the exam.
(b) Some tutorials you see will declare the script as type “JavaScript” and encase the
JavaScript as a HTML comment block but this is unnecessary with newer browsers.
(c) Each JavaScript command line generally ends with a semicolon (;).
(d) JavaScript is case-sensitive, which means that there’s a difference between upper-
case and lowercase characters and it will be important to be precise when typing
JavaScript code.
2. You will notice that this code will cause a window to pop up when you load the HTML
file. Basically, the script executes on loading of your HTML file.
3. If you want the script to be triggered instead, we are now going to put the code into a

21
function which will be called.
Note: These are called DOM Events. The one we will be exploring for now is the onclick
event but there are others (See Section 12.1).
1 // Put the code in a script element
2 <script>
3 // You declare a function using the function keyword
4 // The function name can anything but must match the onclick event later.
If you are getting errors, remember that JavaScript is case-sensitive.
5 function PopUp() {
6 window.alert ("Triggered pop-up");
7 }
8 </script>
9
10 // Adding an onclick listener to a HTML element
11 <button onclick="PopUp()">Click me to run script</button>

Note:
(a) A JavaScript function is declared with the function keyword.
(b) The function has no arguments. You can use functions with arguments.
(c) This is an example of an event handler. You can read more about it here.
Something will “listen” for a change, and something else will execute.
(d) In this example, onclick is one example of a DOM event. There are others that you
can check out here.
(e) One thing you will notice in our code is that the onclick is tied to one function but
you can include two (or more):
1 onclick="doThisFunction();thenDoTheOtherFunction();"

(f) As onclick is an attribute, it is not the only HTML element it can be applied to. You
can add it to a paragraph element:
1 <p id="demo" onclick="ChangeColour()">Click to change color.</p>
2
3 // Here the script is added after the call of it.
4 // The order of how the scripts appear do not normally matter unless
you are running one after the other (e.g. the earlier example) and
the second script may be the only one that runs
5 <script>
6 function ChangeColour() {
7 document.getElementById("demo").style.color = "red";
8 }
9 </script>

(g) Try adding two JS functions to a single onclick attribute.

22
4. For submission: Create a form that collects a name and e-mail address that shows a pop-
up when you hover your mouse over the input boxes.
Filename: form_popup.html
5. For submission: Use the same form but use embedded CSS (hint: hover) to create a tool-
tip rather than a pop-up.
Filename: form_hover.html

12.1 DOM on-event handlers

So far, we have looked at how the onclick even handler works. There are two common styles:

• a set of specific on-event handlers.


• the generalized addEventListener()

The on-event handlers are a group of properties offered by DOM elements to help manage how
that element reacts to events. Elements can be interactive (e.g. links, buttons, images, forms) or
non-interactive (e.g. the base document).

Events are the actions like being clicked, detecting pressed keys, getting focus, etc. The on-
event handler is usually named according to the event it is designed to react to, such as onclick,
onkeypress, onfocus, etc.

12.1.1 Inline events

You can specify an on<...> event handler for a particular event (such as click) for a given object
in different ways:

• Using an HTML attribute named on-eventtype on an element, for example:


1 <button onclick="return handleClick(event);">,

This was what we were doing earlier, but in this specific example, the code shown includes
a return value and a parameter. Things to note about using the HTML attribute:

1. Used to indicate which event to target.


2. An event handler is embedded in an HTML tag as an attribute and indicates some
JavaScript code to execute when the event occurs.
3. Use the event name with the prefix “on”.

23
Event Event handler Triggered when:

click onclick when the user clicks on an object

load onload the browser renders (loads) a web page

mouseover onmouseover the mouse cursor is over an object

mouseout onmouseout when the mouse cursor moves away from an object
that it had previously hovered over

submit onsubmit when the submit button on the form is clicked

unload onunload when the web page unloads in the browser (hap-
pens just before a new web page loads)
You can find a more comprehensive list: here.

• by setting the corresponding property from JavaScript, for example:


1 <document.getElementById("mybutton").onclick = function(event) { ... }

Note: that each object can have only one on-event handler for a given event (though that
handler could call multiple sub-handlers). This is why addEventListener() is often the
better way to get notified of events, especially when wishing to apply various event han-
dlers independently from each other, even for the same event and/or to the same element.

12.1.2 Event listeners

This is how you can use addEventListener().


1 // The function you want to invoke. This is another way of declaring it.
2 var myFunctionReference = function() { /* do stuff here*/ }
3 // Notice that the event name is WITHOUT the "on". Rather than "onclick" or "
onmouseover" it is just "click" and "mouseover".
4 element.addEventListener(’click’, myFunctionReference , false);

You can try the full code here:


1 // Declare your element with an id that matches the function
2 <div id="demo">The original text</div>
3
4 <script>
5 // Declaring the changeContent function
6 function changeContent(){
7 document.getElementById("demo").innerHTML = "The contents have
changed!";
8 }

24
9 // Here is where you include the addEventListener
10 document.addEventListener("click", changeContent, false);
11 </script>

Task 4: On-event triggers


In this task you will be testing out two on-event handlers.

1. Type out this code. In this code, we will embed the JavaScript within the tag itself.

Reminder

Caution: when testing this code out, it can get annoying as pop-up
messages will appear. If you use Internet Explorer, your computer
may not stop responding as many pop ups will appear. If you test
this code with Firefox, you may receive a pop-up message. If this
happens, and if your browser allows you to disable pop-ups from the
site, your script will appear as if it is not working.

1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <title>On-event Practice</title>
5 <meta charset="utf-8">
6 </head>
7
8 <body>
9 <h1>Using on-event</h1>
10 <ul>
11 // There is no need to declare the function within the <script> element
for this code
12 <li onmouseover="alert(’Mouse over’);">Mouseover test</li>
13 <li onmouseout="alert(’Mouse out’);">Mouseout test</li>
14 // Each attribute calls the "alert" method
15 </ul>
16 </body>
17 </html>

Note:
(a) Did you notice that there is no <script> element? Why does it still work? Look at
this code and the comments:

25
1 onmouseover="somemethod(somesupportedinput)"

Notice that the attribute onmouseover calls the somemethod method that takes as
an input somesupportedinput. When you look at this:
1 alert(’Mouse over’);

Do you notice that the alert itself is a method that takes a String input? The onevent
attribute will call JavaScript methods.
(b) The JS code was written within the tag itself. You can write this as a separate
function.
(c) There is no difference in using single and double quotes in HTML and JS (There
is a difference in PHP). The only reason single and double quote are mixed in this
example is to show the fact that you can mix them.
(d) Let’s try to explain why even when you do not point your cursor directly over the
words the alert box pops up. First, open the Element Inspector. Next, look at the
Box Model Properties of the list item (i.e. the <li>. You will notice that each of
the list items are display:list-item and spans the entire width of the viewport.
• What can you conclude from this observation?
• What can you do to the code so that only when the mouse is over the words will
the alert be triggered?
This is why you can call the alert method without first declaring a function within a
<script> element.
2. Move your mouse:
• On and off: OVER the words
• On and off: ON THE SAME LINE as the words
3. Record your observations.
4. Modify your file so that the alert:
• Only appears when you point your mouse over THE WORDS.
• are in a(nother) function.
• use the addEventListener()
Save this file as: onmouseover_out_event.html
5. (Mini challenge) Further modify your file so that the alert:
• You can count how many times the mouse has triggered the event and display it.
• Stop displaying the event after showing FIVE (5) times.
• Start displaying the event again after the user has gone over the worlds TEN (10)
times.
Save this file as: onmouseover_out_event_minichallenge.html
Note: This is a challenge question as it will require you to know some other topics: declar-

26
ing and using variables, arithmetic operations and branching (or conditional) statements.

Question(s) 5

1. Describe how a web site is hosted on a web server and a web page retrieved
using the idea of ports.
2. (Challenge) What do you need to do on a router if you intend to host your web-
site from a web server within your company to be accessed by others outside
your company?
Note: In an earlier lab, you have tested and seen how you can access another
computer’s web server from within the same network (i.e. the lab). This ques-
tion asks for what you need to do if the other person (or client) is not within the
same network.
3. In programming:
(a) what is the difference between an object and a class?
(b) what is a method?
(c) what is a property?
4. Can you use a JavaScript method to change an element’s property? If so, de-
scribe how. If not, explain why not.

Task 5: Appending lines to HTML


We have so far learnt to trigger a script (using onevent handlers) and how to make changes
to the HTML DOM7 . In this task, you will adding new elements (i.e. appending them) to the
<body> of your HTML DOM by triggering the code to execute. From this task, I will also
want you to see the difference between a HTML file and the HTML DOM (which is what you
see in your browser window).

1. In a new file, insert the following code.


1 // This line is just to add a trigger for your script
2 <p onmouseover="appendToFile()">Paragraph to trigger</p>
3
4 <script>
5 function appendToFile() {
6 let div = document.createElement(’div’);
7 div.className = "alert";
7
Why did I say HTML DOM and not the HTML file? After the script runs, look at the HTML DOM using
the Inspector, does it match the HTML file? What do you think the script did: change the HTML file or just the
HTML DOM (which you are viewing in your browser)?

27
8 div.innerHTML = "You’ve added a new line.";
9
10 document.body.append(div); // Used to append the <div> element
to the body of the HTML DOM
11 }
12 </script>

Note:
(a) We used let to declare a constant. (See Line 6. A constant will not change and is
different from a variable. Think of a constant like the value of pi(π).
(b) Lines 7 and 8 is used to set different properties of the <div> element.
(c) As the comment has already pointed out, Line 10 appends or adds a new <div>
element to the HTML DOM <body>.
2. Check your browser’s Inspector and compare the DOM shown in the Inspector with your
HTML file.
3. Now, try this:
(a) Create a database and a HTML form that will accept: A student’s name, their Stu-
dent ID and their course.
(b) Populate your database with some values (around 5 names).
(c) Create a table that will display the values from the database.
Note: If there are names added into the database at a later date, your table should be
able to automatically show additional names when the page is refreshed.
Note: This task is not limited to JavaScript and you can use a combination of whatever
you have learnt.
Save this file as: append_to_table.html
4. Try sorting the values before displaying the data in the table. The sorting criteria and how
you plan to go about it is up to you.

Task 6: Getting user input


Note: For this task, you will need to know how to declare variables, assign a value to them and
display your values (using any one of the methods above).

In this task, you will be learning how to get an input from a user:

1. Create a HTML file with the following script.


1 <script>
2 // Declaring a variable
3 var yourName;

28
4 // Creating the prompt
5 yourName = prompt("Please enter your name");
6 // This can also be written as
7 yourName = window.prompt("Please enter your name");
8 // To display what was entered
9 document.write("<h1>Hello " + yourName + "</h1>");
10 </script?

Note:
(a) You can use window.prompt and it was omitted because it is understood that the
prompt will be a window.

Task 7: Testing non-in-browser JavaScript


If you have any experience with Python, this is going to be very similar, in a way that both will
need interpreters and a runtime to run the scripts.

1. Download and install node.js from here.


Note: If you are doing this on the lab’s computer, you will not have admin rights to use
the installer version. You will have to use the “Windows Binary” version - either the 32-
bit or 64-bit version.
Note:
(a) If you have installed node.js and restarted your computer, a PATH to the node exe-
cutable will have been added and you will be able to run your JS file from any path
of the command prompt.
(b) If you have the binary version, you will have to extract the files. The executable
node will be in the extracted folder. This means to execute node, you will need
to navigate to this folder in your command prompt. To make it easier to get to this
folder, you can use File Explorer to first get to that folder and then open a command
prompt by going to the Address Bar and type in “cmd” and press the Enter key. A
Command Prompt should open up in the folder you have navigated to.
2. Create a JavaScript file:
1 // Declaring some variables
2 var a=1;
3 var b=10;
4 var sum=a+b;
5
6 // Printing the value out
7 console.log("The sum is: " + sum);

29
Save the file as: node1.js
You need to know where you saved this file as you will need the location to run it.
3. To run the JS file, navigate to the location where you run the saved file by typing:
node node1.js
Notice that this is similar to running a Python script (in non-interactive mode). You will
have to modify either the path to your JS file or to the node executable if they are not in
the PATH or in the same folder.
4. You can of course substitute the JS code with your own.

Task 8: Checking your form for errors


You are going to be checking your form for errors. This is highly related to the earlier lab on
creating forms. You need to know what to expect of the incoming data and validate accordingly.
This was mentioned in the lab on forms.

1. Create this form (if you have not done so in an earlier lab):

(a) First name (h) Address Line 1


(b) Last name (i) Address Line 2
(c) Student ID (j) Postcode
(d) Course taken in Sunway (k) City
(e) Date of Birth (l) Country
(f) E-mail address (m) Preferred contact method
(g) Mobile number (phone, e-mail or post)

2. Setup the form to use the correct input types.


For submission: For each of the form fields, state the input type that should correspond
to that field. (For obvious reasons, this should not all be text)
Submit your file as: input_type.txt
Your file should be formatted this way:
1 Fist name: text
2 Last name: .....

3. Add JavaScript checks for the inputs using functions. You are left to decide how an error
should be displayed to the user. Examples include (but not limited to):
• Highlighting the input
• Highlighting the label
• Pop-up box
Hint: It is not useful to just tell the user that an error has occurred or an invalid input
entered. You should inform the user of what kind of input you are expecting.
For submission: Submit your file as: form_with_checks.html

30
4. Ensure the following:
• Do not refresh the page and lose all the inputs entered because of a single error. This
will force the user to enter all previously entered data.
Although not covered, you could use other methods of saving a page data (session
and cookies).
• Your form has a usable design/style with the correct sizes for the boxes.
5. Other notes:
• There are many ways to choose the different elements to check their inputs. One
of it is to use the index of an array that is returned when using document.forms[].
Let’s look at an example:
1 <script>
2 function validateForm(){
3 if (document.forms[0].userAge.value < 18){
4 alert ("You are too young");
5 return false;
6 } // end if
7 else {
8 alert("Age is valid");
9 return true;
10 }
11 } // end of function validateForm
12 </script>

However, recall that if you do it this way (rather than selecting by class or id name),
the input elements in your form cannot change as a certain order is expected. In this
code, it is expected that the age is the first element. Now, imagine that you added an
input for the user’s name before the age. Now, the age is NOT the first input and the
index[0] no longer refers to the age. What do you think happens to the validation?

13 Summary
This lab was to introduce you to JavaScript (and perhaps scripting in general). At the end of
this lab:

1. You will understand the idea of ports and how they relate to processes on your computer.
2. You will know what DOM is and how to use it in your code.
3. You will know what DOM DataTypes and Events are.
4. You will be able to display an alert box using JavaScript.
5. How to access different HTML elements using JavaScript and be able to read or write to
their values.

31
14 References
1. JavaScript Async and Defer
2. JavaScript Async and Defer 2
3. W3.org Introduction to the DOM
4. MDN DOM
5. How do I write JavaScript
6. HTML vs DOM

Submission
In your submission archive, you should have the following files/folders:

1. All the named files in this lab


2. Exported copies of your database table in any importable format (e.g. CSV).
3. Answers to questions in a PDF file

Ensure the following:

1. The file is correctly named and in the correct format. The naming convention is found on
eLearn but for the sake of completeness, for this lab it will be:
<ID>_<labNum>.zip, where:
• <ID> is your student ID, and
• <labNum> is the number of this lab.
2. Do not use any other archive type. The file you submit must be the zip format. If you
are using your laptop and do not have that software, you can download a free zip archive
creator from the 7zip download page. If you are using 7zip, remember to change the
archive format to ZIP. For Mac users, you can use Keka.

The submission link will be found on eLearn. Adhere to the guidelines and instructions on
eLearn.

32
Changelog
• Version: 1.6.5
Date: 6 Nov 2020
1. Corrected: Single and double quotation marks
2. Added: A note about single and double quotes.
3. Updated: Task 3. Added some questions and an additional task.

• Version: 1.6.4
Date: 4 Nov 2020
1. Corrected: Codes on Pg.17 and Pg.26.
2. Corrected: Formatting issues for the “Summary”.
3. Updated: Clarified Q3.2 on what is meant by “a remote file located on a server” by
adding a note.

• Version: 1.6.3
Date: 15 Nov 2019
1. Corrected: The Lab number.

• Version: 1.6.2
Date: 13 Nov 2019
1. Updated: Changed all the JS to JavaScript, corrected page breaks and alignments, added
comments to some of the codes
2. Removed figure for what JavaScript can do.
3. Correction in the function call for appending lines to HTML

• Version: 1.6
Date: 12 Nov 2019
1. Added: addEventListener with code examples.
2. Changed: a task to include the use of AddEventListener

• Version: 1.5.1
Date: 11 Nov 2019
1. Added: a task to append.

• Version: 1.5
Date: 11 Nov 2019
1. Added: a small part on using prompts.

• Version: 1.4
Date: 8 Nov 2019
1. Removed: Previously Task 6 - on data confirmation before saving that was more PHP
based and will be moved to the “more tasks” in another lab sheet.

33
2. Updated: A lab roadmap and how the different tasks fit in. Futurework: Will add some-
thing similar to other labs if it helps students understand what they are doing.
3. Added an explanation for the on-event section
4. Revised: The summary. Removed a spurious summary.

• Version: 1.3
Date: 7 Nov 2019
1. Added: node.js task, prerequisites, notes about having some programming basics.

• Version: 1.2
Date: 6 Nov 2019
1. Corrected: Question 1’s hanging sentence.
2. Added: on-event handlers
3. Added: Task for on-event handlers
4. Changed: PDFpagelayout from double to single.

• Version: 1.1
Date: 6 Nov 2019
1. Removed bits of the writing that should have been commented out.
2. Extensive rewriting of the DOM part.
(a) Added an explanation between HTML and DOM
(b) Illustrated the DOM as a tree (apart from just a diagram)
3. Added: async vs defer for the evaluation of scripts.
4. Added: a note and a step in a task on how to use the Web Console to troubleshoot scripts
5. Added: Links in the PDF bookmark to tasks.
6. Updated: Changed the colours of the filesubmissions to make them more visible.
7. Corrected: various spelling mistakes and alignment issues
8. Corrected: Table 1. The formatting in v1.0 was incorrect and off.

• Version: 1.0
Date: 4 Nov 2019
1. Rewrote part of the lab sheet. Work in progress.

34

You might also like