Lab 9: Javascript Web1201: Web Fundamentals: Rev 1.6.5 November, 2020
Lab 9: Javascript Web1201: Web Fundamentals: Rev 1.6.5 November, 2020
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:
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:
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.
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.
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 a few things that makes JavaScript a choice for web developers:
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.
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.
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:
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:
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.
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”)
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:
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
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>
Question(s) 3
8
(a) CSS file
(b) JavaScript file
(c) image file
(d) a binary file intended for users to download
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.)
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:
Figure 1: Visualization of how async and defer affects script loading and execution. Redrawn
from here.
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.
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>
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
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.
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.
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.
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?
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
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.
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
18
Method 2: Using document.write
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>
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.
The alert message box is displayed using the alert() method. We have already seen it being
used in an earlier example.
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>
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
So far, we have looked at how the onclick even handler works. There are two common styles:
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.
You can specify an on<...> event handler for a particular event (such as click) for a given object
in different ways:
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:
23
Event Event handler Triggered when:
mouseout onmouseout when the mouse cursor moves away from an object
that it had previously hovered over
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.
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.
24
9 // Here is where you include the addEventListener
10 document.addEventListener("click", changeContent, false);
11 </script>
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.
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.
In this task, you will be learning how to get an input from a user:
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.
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.
1. Create this form (if you have not done so in an earlier lab):
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. 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