document is a special object referring
to the document displayed in the browser window
write is a method defined on an HTML
document, which writes text into it
title is a property defined on document,
which retrieves the title
Events
more commonly, scripts are executed in response to events, e.g, clicking a button
the following button
was produced using (old style):
<button onClick="window.alert('Hello World!')">
Click to see a message
</button>
the button element creates a button
what is displayed on the button is specified by the contents of the button element
Event explanation
<button onClick="window.alert('Hello World!')">
onClick is an event attribute
window is a DOM object representing
the browser window
alert is a method of window,
which opens a new window displaying the message given as argument
here the script is embedded in the value of the onClick attribute
best practice dictates that HTML and Javascript should be separated
Calling a function
say we want to call a function when a button is clicked
we can use the following code (still old style):
<button onclick="tableOfSquares()">Click to produce
table of squares</button>
this will produce the button
which calls the user-defined function tableOfSquares
we need somewhere on the page to write the table
we use an empty div element with id="tos" on the next slide
Function output
Table of squares function
the following function produces a table of squares of the first
n integers, where n is entered by the user:
function tableOfSquares() {
// Display a prompt with a zero in it
const num = window.prompt("Enter an integer", "0");
let myTable = "<table class='border'>";
let count = 0;
while(count < num) {
// Each row contains an integer and its square
myTable = myTable + "<tr><td>" + count + "</td><td>"
+ count*count + "</td></tr>";
count++;
}
document.getElementById("tos").innerHTML = myTable +
"</table>";
}
Comments on previous script
a comment is indicated by // (to end of line)
const declares a constant
let declares a variable (creates a binding)
variables do not need to be declared before use, nor are they
statically typed
a variable can be initialised with a value, e.g.,
count is set to zero
prompt is a method of window,
which opens a dialog box with the given message and default value
for the input; it returns the value entered by the user
More comments
myTable is used to store a string representing an HTML table
JavaScript has the usual while and for loops
+ is used for string concatenation
count++ adds one to the value of the variable count
getElementById is a document method
returning a reference to the identified element
innerHTML is a property of DOM nodes which can be set by assigning
to it a string representing HTML
Functions in JavaScript
the previous function was defined using a function declaration:
function tableOfSquares() { ... }
it can also be defined using a binding:
const tableOfSquares = function () { ... }
or using an arrow:
const tableOfSquares = () => { ... }
note that this function has no parameters
Defining a function
function tableOfSquares has to be defined somewhere, either
in a script element in the document, or
in an external file with the extension js
in our case, all functions are
defined in the external file client.js
this file is referenced in the head of this document
as follows:
<script type="text/javascript" src="client.js" />
JavaScript console
web browsers provide a way of running and debugging JavaScript code
in Firefox, this is found using the Web Developer → Web Console menu item
output to the console is done as follows:
console.log(document.title);
which produces
Client-Side Processing
← undefined
because console.log does not return a value; the output is a side-effect
Event handlers
the value of an onclick attribute is an event handler
rather than embedding the event handler code in the HTML, it is preferable to
bind the click event to the button, and
associate a handler function with the event
in Javascript code separate from the HTML
Event handlers example
now the code for the button (which we need to be able to identify) is:
<button id="hello-button">Click to produce message</button>
the code for binding the click event to the button
and associating an event handler function is:
will call myTranslate (next slide)
when the button is clicked
Defining function myTranslate
function myTranslate is
defined as follows:
function myTranslate() {
const word = document.getElementById("myWord").value;
let result = "unknown";
if (word === "hello")
result = "buongiorno";
else if (word === "goodbye")
result = "arrivederci";
document.getElementById("myResult").value = result;
}
word contains the word the user entered
value refers to the contents of the identified input
elements
Equality in JavaScript
JavaScript has two equality operators: == and ===
== tests if two values are equal (possibly after type coercion)
=== tests if both the types and values are equal, so is considered safer
e.g., (1 == true) is true, while (1 === true) is false
Navigating the DOM tree
each DOM node object has a number of properties for navigation, e.g.:
firstChild
nextSibling
parentNode
childNodes
which return, respectively, the first child,
next sibling, parent and all children of the node
Other DOM node properties
other properties include
nodeName (return the name of an element node)
nodeValue (return the textual content of a text node)
often easier to navigate using the getElementsByTagName method:
takes an element name as argument
returns a collection of all element nodes with that name
Finding elements by name
say we want to output the value of each option element in the current document
we want them to appear as a list below when the following button is clicked:
Finding elements (function body)
we can use the following script:
const options = document.getElementsByTagName("option");
let output = "<ul>";
for ( i = 0; i < options.length; i++ )
output = output + "<li>" +
options[i].firstChild.nodeValue + "</li>";
document.getElementById("optionList").innerHTML = output +
"</ul>";
getElementsByTagName returns a collection of nodes
length is a property of a collection;
it returns the number of items in the collection
Function body (continued)
for ( i = 0; i < options.length; i++ )
output = output + "<li>" +
options[i].firstChild.nodeValue + "</li>";
document.getElementById("optionList").innerHTML = output +
"</ul>";
the i'th item in a collection can be retrieved
using array-like indexing
firstChild is a property of a node;
it returns the first child of the node if it exists,
otherwise null
nodeValue is a property of a node;
it returns the text value if it is a text
node, otherwise null
an element with textual contents is represented by an element node
having a single text node as a child
Using CSS selectors
the DOM also provides the methods
querySelector
querySelectorAll
which each take a CSS selector as argument
querySelector returns the first matching node
querySelectorAll returns all matching nodes
instead of getElementsByTagName("h1")
we could use querySelectorAll("h1")
instead of getElementById("optionList")
could use querySelector("#optionList")
More complex selectors
we could also use selectors
div.slide to find all div elements with class value slide
div li to find all li elements within div elements
div.slide > h1 to find all h1 elements which are children of div elements with class value slide
a[href^='http'] to find all a elements with an href attribute whose value starts with http
states will be used to populate the drop-down list
Code for JSON retrieval (1)
the code is as follows:
$('#addressCountry').change(
function() {
// Remove all of the options
$('#addressState').empty();
if (this.value === 'na') return;
$.getJSON(
... see next slide
);
}
);
change (rather than click) event is needed
for select in Chrome and Safari
jQuery provides a getJSON function
which retrieves a JSON file from the server
Code for JSON retrieval (2)
the code for getJSON call is as follows:
$.getJSON(
this.value + '.json',
function(json) {
// Change the label
$('label[for="addressState"]').text(
json.label + ':'
);
... see next slide
}
);
first argument is the name of the file
second argument is a function to be called on success and passed the JSON data
Code for JSON retrieval (3)
the code for setting the options is as follows:
$.each(
json.states,
function(id, state) {
... see next slide
}
);
each iterates over each key/value pair
of states
for each one, the function is called and passed the key and value
(id and state)