<script>
element specifies script to be executed
type
attribute has value text/javascript
src
attribute specifies URI of external script<script>
appears in the
<head>
and just declares functions to be called laterscript
element being encountered in a document (not recommended)load
, unload
click
, mouseup
, mousemove
keydown
, keyup
submit
play
<script type="text/javascript"> document.write("<em>Document title</em>: ", document.title); </script>inside an HTML table cell (not recommended)
document
is a special object referring
to the document displayed in the browser windowwrite
is a method defined on an HTML
document
, which writes text into ittitle
is a property defined on document
,
which retrieves the title<button onClick="window.alert('Hello World!')"> Click to see a message </button>
button
element creates a buttonbutton
elementonClick
is an event attributealert
is a method of window
,
which opens a new window displaying the message given as argumentonClick
attribute<button onclick="tableOfSquares()">Click to produce table of squares</button>
tableOfSquares
li
element with id="tos"
function tableOfSquares() { // Display a prompt with a zero in it var num = window.prompt("Enter an integer", "0"); var myTable = "<table class='border figure'>"; var count = 0; while(count < num) { // Each row of the table is an integer and its square myTable = myTable + "<tr><td>" + count + "</td><td>" + count*count + "</td></tr>"; count++; } document.getElementById("tos").innerHTML = myTable + "</table>"; }
var
declares a variablecount
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 usermyTable
is used to store a string representing an HTML tablewhile
and for
loop constructs+
is used for string concatenationcount++
adds one to the value of the variable count
getElementById
is a document method
returning a reference to the identified elementinnerHTML
is a property of DOM nodes which can be set by assigning
to it a string representing HTMLtableOfSquares
has to be defined somewhere, either
script
element in the head
of the document, orjs
client.js
head
of this document
as follows:
<script type="text/javascript" src="client.js" />
onclick
attribute is an event handlerclick
event to the button, and
<button id="hello-button">Click to produce message</button>
click
event to the button
and associating an event handler function is:
document.getElementById("hello-button").onclick = helloAgain;
helloAgain
is simply the name of the function
to be calledhello-button
is only available after the page has loadedclick
event to the
button, as follows:
window.onload = function() { document.getElementById("hello-button").onclick = helloAgain; }
load
event to the window
objecthelloAgain
helloAgain
is defined as follows:
function helloAgain() { window.alert("Hello again world!"); }
onclick
property (attribute) of an element:
document.getElementById("hello-button").onclick = helloAgain;
document.getElementById('hello-button').addEventListener('click', helloAgain);
helloAgain
when the click
event occursremoveEventListener
<form> <label>Enter a word:</label> <input type="text" id="myWord" /> <input type="button" id="myButton" value="Translate" /> <input type="text" id="myResult" /> </form>
form
element indicates an HTML forminput
element (with type="text"
) creates a single-line textboxinput
element (with type="button"
) creates a button with the
given value
displayed on itmyWord
, myButton
and myResult
identify the
input
elements of the form
document.getElementById("myButton").onclick = myTranslate;will call
myTranslate
(next slide)
when the button is clickedmyTranslate
myTranslate
is
defined (in client.js
) as follows:
function myTranslate() {
var word = document.getElementById("myWord").value;
var result = "unknown";
if (word === "hello")
result = "buongiorno";
else if (word === "goodbye")
result = "arrivederci";
document.getElementById("myResult").value = result;
}
word
contains the word the user enteredvalue
refers to the contents of the identified input
elements==
and ===
==
tests if two values are equal (possibly after type coercion)===
tests if both the types and values are equal, so is considered safer(1 == true)
is true, while (1 === true)
is falsenode
object has a number of properties for navigation, e.g.:
firstChild
nextSibling
parentNode
childNodes
nodeName
nodeValue
getElementsByTagName
method,
which takes an element name as argument and returns a collection of all element nodes
with that nameh1
elements from the current documentvar headings = document.getElementsByTagName("h1"); var output = "<ul>"; for ( i = 0; i < headings.length; i++ ) output = output + "<li>" + headings[i].firstChild.nodeValue + "</li>"; document.getElementById("headingList").innerHTML = output + "</ul>";
getElementsByTagName
returns a collection of nodeslength
is a property of a collection;
it returns the number of items in the collectionitem(i)
as a method call or using array-like indexingfirstChild
is a property of a node;
it returns the first child of the node if it exists,
otherwise it returns nullnodeValue
is a property of a node;
it returns the text value of the node if it is a text
node, otherwise it returns nullquerySelector
querySelectorAll
querySelector
returns the first matching node,
while querySelectorAll
returns all matching nodesgetElementsByTagName("h1")
we could use querySelectorAll("h1")
getElementById("headingList")
we could use querySelector("#headingList")
div.slide
to find all div
elements with class value slide
div li
to find all li
elements within div
elementsdiv.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
<button id="addButton">Add li element</button>
click
event handler is assigned as follows:
document.getElementById("addButton").onclick = addElement;
ul
element on this slide is identified by id="target1"
addElement
is defined as follows (in client.js
):
function addElement() { var elem = document.getElementById("target1"); var node = document.createElement("li"); var text = document.createTextNode("Hello"); node.appendChild(text); elem.appendChild(node); }which appends a new
li
element to the identified ul
elementcreateElement
is a method which
creates an element with the given namecreateTextNode
is a method which
creates a text node with the given valueappendChild
is a method of a
node
; it appends the given node to the list of the node's
children<button id="deleteButton">Delete ul element</button>
click
event handler is assigned as follows:
document.getElementById("deleteButton").onclick = deleteElement;
ul
element on this slide is identified by id="target2"
deleteElement
is defined as follows (in client.js
):
function deleteElement() {
var elem = document.getElementById("target2");
elem.parentNode.removeChild(elem);
}
which deletes the identified ul
elementremoveChild
is a method of a
node
; it removes the given node from the list of the node's
childrenjquery-3.3.1.min.js
is referenced by these pagesdeleteElement
function, we could use
function() {$('#target2').remove();}
$
remove
method deletes the elements on which it is invokedaddElement
function, we could use
function() {$('#target1').append($('<li />', {'text':'Hello'}));}
append
method adds a new last child to elements on which it is invoked$
creates a new element when passed a
string representing an empty element as first argumenttext
property is interpreted as the textual contents of the elementvar ul = $('#headingList').append($('<ul />')); $('h1').each(function() { ul.append($('<li />', {'text': $(this).text()})); });
each
iterates over a set of elements;
the function it takes as argument is called for each elementthis
returns the element on which
the function is calledtext
returns the textual contents of an elementrss-fragment.xml
<rss> <channel> <title> ... </title> ... <item> <title> ... </title> <description> ... </description> <link> ... </link> <pubDate> ... </pubDate> </item> ... <item> <title> ... </title> <description> ... </description> <link> ... </link> <pubDate> ... </pubDate> </item> <channel> </rss>
$.get("rss-fragment.xml",
function( xml ) {
...
},
"xml"
);
get
method of jQueryid
of the above button is listButton
client.js
we bind a function name to the click event for the button:
document.getElementById("listButton").onclick = findItemTitles;
div
element below, with id="TitleList"
findItemTitles
simply executes the code on the previous slide
where the body of the function is:
var titles = xml.querySelectorAll("item > title")
var output = "<ul>";
for ( i = 0; i < titles.length; i++ )
output = output + "<li>" + titles[i].firstChild.nodeValue + "</li>";
document.getElementById("TitleList").innerHTML = output + "</ul>";
<form> <fieldset> <legend>Address</legend> <select id='addressCountry'> <option value='na'>Please select a country</option> <option value='ca'>Canada</option> <option value='gb'>United Kingdom</option> <option value='us'>United States</option> </select> <label for='addressState'>County/Province/State:</label> <select id='addressState'></select> </fieldset> </form>
ca.json
, gb.json
and us.json
gb.json
) looks as follows:
{ "name" : "United Kingdom", "iso2" : "GB", "iso3" : "GBR", "label" : "County", "states" : { "0" : " ", "794" : "Angus", ... "988" : "York" } }
label
gives the correct term for County/Province/Statestates
will be used to populate the drop-down list$('#addressCountry').change( function() { // Remove all of the options $('#addressState').empty(); if (this.value === 'na') return; $.getJSON( this.value + '.json', function(json) { // Change the label $('label[for="addressState"]').text( json.label + ':' ); ... see next slide } ); } );
change
(rather than click
) event is needed
for select
in Chrome and SafarigetJSON
function
which retrieves a JSON file from the server
// Set the options ...
$.each(
json.states,
function(id, state) {
$('#addressState').append(
$('<option/>')
.attr('value', id)
.text(state)
);
}
);
each
iterates over each key/value pair
of the states
id
and state
)option
is added each time, with its value
attribute
set to the id
of the state and its text set to the value of state
celsius
returns the Celsius equivalent
of a Fahrenheit temperature using the calculation C= 5.0/9.0 * (F-32)fahrenheit
returns the Fahrenheit
equivalent of a Celsius temperature using the calculation
F = 9.0/5.0 * C + 32onClick
attributes.
(see slide 15 and slide 16.)
onClick
attributes
but instead binds events to the buttons. Remember to use window.onload
to delay the bindings until after the page has loaded (as in slide 13).
titan.dcs.bbk.ac.uk/~...
, where ...
is your username. Your HTML page will also need to reference the jQuery library,
either remotely or by saving a copy in your web space. The version I use is
here.www.webteacher.com/javascript/
www.w3schools.com/js/default.asp
www.w3.org/DOM/
www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ecma-script-language-binding.html
www.w3schools.com/dom/default.asp
There are many books devoted to Javascript and/or jQuery. DOM is covered in Chapter 7 of [Moller and Schwartzbach] and Chapter 8 of [Jacobs]. See above for books on jQuery.