COMP519 Web Programming
Lecture 17: JavaScript (Part 8)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
1 Dynamic Web Pages Using JavaScript
Document Object and Document Object Model
Accessing and Manipulating HTML Elements
2 Event-driven Programs
Introduction
Events
3 Extended Example
4 Further Reading
COMP519 Web Programming Lecture 17 Slide L17 1
Dynamic Web Pages Using JavaScript Document Object and Document Object Model
Window and Document objects
JavaScript provides two objects that are essential to the creation of
dynamic web pages and interactive web applications:
document object
an object-oriented representation of a web page (HTML document) that
is displayed in a window
allows interaction with the Document Object Model (DOM) of a page
Example: document.writeln() adds content to a web page
Document Object Model
A platform- and language-neutral interface that allows programs and
scripts to dynamically access and update the content, structure and style
of HTML, XHTML and XML documents
COMP519 Web Programming Lecture 17 Slide L17 2
Dynamic Web Pages Using JavaScript Document Object and Document Object Model
Document Object Model
Example:
The HTML table below
<table >
<tbody >
<tr >
<td >Shady Grove </ td >
<td > Aeolian </ td >
</tr >
<tr >
<td > Over the River , Charlie </ td >
<td > Dorian </ td >
</tr >
</tbody >
</table >
is parsed into the following DOM
Arnaud Le Hors, et al, editors: Document Object Model (DOM) Level 3 Core Specification, Version 1.0,
W3C Recommendation 07 April 2004. World Wide Web Consortium, 2004.
https://www.w3.org/TR/DOM-Level-3-Core/ [accessed 9 January 2017]
COMP519 Web Programming Lecture 17 Slide L17 3
Dynamic Web Pages Using JavaScript Document Object and Document Object Model
Accessing HTML Elements: Object Methods
Example:
// access the tbody el ement from the table eleme nt
var myT body Ele m ent = m y Tab leEl eme n t . fi rst Chi ld ;
// access its secon d tr e lem en t ; the list of child ren starts at 0 ( not 1).
var myS e con d TrEl emen t = myTb ody E lem ent . c hil dNo des [1];
// remove its first td elem ent
my S econ dTrE leme n t . re mov eCh ild ( m ySec ondT r Ele m ent . fir stCh ild );
// change the te xt co ntent of the re mai nin g td el ement
my S econ dTrE leme n t . fi rst Chi ld . f irs tCh ild . data = " Peter ";
COMP519 Web Programming Lecture 17 Slide L17 4
Dynamic Web Pages Using JavaScript Accessing and Manipulating HTML Elements
Accessing HTML Elements: Names (1)
Instead of using methods such as firstChild and childNodes[n], it is
possible to assign names to denote the children of an HTML element
Example:
< form name =" form1 " actio n ="" >
<label > Temperature in F a h renheit : </ label >
< input type =" text " name =" f a h r e n h e i t " size ="10" val ue ="0" > < br >
<label > Temperature in Celsius : </ label >
< input type =" text " name =" c elsius " size =" 10" value ="" >
</ form >
Then document.form1
Refers to the form named form1
document.form1.celsius
Refers to the text field named celsius in document.form1
document.form1.celsius.value
Refers to the attribute value in the text field named celsius
in document.form1
COMP519 Web Programming Lecture 17 Slide L17 5
Dynamic Web Pages Using JavaScript Accessing and Manipulating HTML Elements
Accessing HTML elements: Names (2)
Accessing HTML elements by giving them names and using paths within
the Document Object Model tree structure is still problematic
; If that tree structure changes, then those paths no longer work
Example:
Changing the previous form to
< form name =" form1 " actio n ="" >
<div class =" field " name =" fdiv " >
<label > Temperature in F a h renheit : </ label >
< input type =" text " name =" f a h r e n h e i t " size ="10" val ue ="0" >
</div >
<div class =" field " name =" cdiv " >
<label > Temperature in Celsius : </ label >
< input type =" text " name =" c elsius " size =" 10" value ="" >
</div >
</ form >
means that document.form1.celsius no longer works as there is now a
div element between form and text field, we would now need to use
document.form1.cdiv.celsius
COMP519 Web Programming Lecture 17 Slide L17 6
Dynamic Web Pages Using JavaScript Accessing and Manipulating HTML Elements
Accessing HTML elements: IDs
A more reliable way is to give each HTML element an ID
(using the id attribute) and to use getElementById to retrieve
an HTML element by its ID
Example:
< form id =" fo rm1 " act ion ="" >
Temperature in Fahrenheit :
< input type =" text " id =" fahrenheit " size =" 10" value ="0" > < br >
Temperature in Cel s ius :
< input type =" text " id =" celsiu s " size =" 10" value ="" >< br >
</ form >
Then
document.getElementById('celsius')
Refers to the HTML element with ID celsius document
document.getElementById('celsius').value
Refers to the attribute value in the HTML element with ID celsius
in document
COMP519 Web Programming Lecture 17 Slide L17 7
Dynamic Web Pages Using JavaScript Accessing and Manipulating HTML Elements
Manipulating HTML elements (1)
It is not only possible to access HTML elements,
but also possible to change them on-the-fly
<html >< head > < title > Manip u l ating HTM L ele ment s (1) </ title >
<style >
td . RedBG { b ackgr o und : # f00 ; }
</ style >
<script >
fu n ctio n c h a n g e BackgroundBl u e ( id ) {
do c umen t . g e t Element B y I d ( id ). style . back g round = "#00 f ";
do c umen t . g e t Element B y I d ( id ). i n nerHT ML = " blu e ";
}
fu n ctio n c h a n g eBackground R e d ( cell ) {
cell . c lassN ame = " Red BG ";
cell . i nnerH TML = " red ";
}
</ script > </ head >< body >
< table borde r ="1" > < tr >
<td id ="0" onclick =" changeBa c k g r o u n dBlue ( ' 0 ' );" > white </ td >
<td id ="1" onclick =" changeB a c k g r o undRed ( this );" > white </ td >
</tr > </ table > </ body > </ html >
http://cgi.csc.liv.ac.uk/
~
ullrich/COMP519/examples/jsBG.html
COMP519 Web Programming Lecture 17 Slide L17 8
Dynamic Web Pages Using JavaScript Accessing and Manipulating HTML Elements
Manipulating HTML elements (2)
It is not only possible to access HTML elements,
but also possible to add new ones and remove old ones on-the-fly
<html >< head > < title > Manip u l ating HTM L ele ment s (2) </ title > </ head >
<body >< ta ble bor der ="1" > < tr >
<td oncli ck =" add Left ( this );" > add </ td >
<td oncli ck =" remov e Left ( this . paren t Node );" > remove </ td >
</tr > </ table > < script >
fu n ctio n addL eft ( n ode ) {
// Maint a in a counter that is i ncreme n ted with each call
ad dLef t . coun ter = addL eft . co unte r || 0;
ad dLef t . coun ter ++;
// Crea te a new TD el emen t with coun ter as con tent
newTD = docume nt . create E l ement (' td ' );
newTD . i nnerH TML = addL eft . co unte r ;
newTD . s e tAttri b u te ( ' id ' , add Left . c ount er );
// Add the new TD elem ent befor e the curr ent one
node . p arent N ode . insert B efore ( newTD , node );
}
fu n ctio n r emove L eft ( parent ) {
pa rent . r emoveC h ild ( parent . f i rstCh i ld );
}
</ script > </ body > </ html >
http://cgi.csc.liv.ac.uk/
~
ullrich/COMP519/examples/jsTD.html
COMP519 Web Programming Lecture 17 Slide L17 9
Event-driven Programs Introduction
Event-driven JavaScript Programs
The JavaScript programs we have seen so far
were all executed sequentially
programs have a particular starting point
programs are executed step-by-step,
involving control structures and function execution
programs reach a point at which their execution stops
COMP519 Web Programming Lecture 17 Slide L17 10
Event-driven Programs Introduction
Event-Driven JavaScript Programs
Web applications are event-driven
; they react to events such as mouse clicks and key strokes
nickywalters: What is Event Driven Programming?
SlideShare, 7 September 2014.
https://tinyurl.com/ya58xbs9 [accessed 5/11/2017]
With JavaScript,
we can define event handler functions for a wide variety of events
event handler functions can manipulate the document object
(changing the web page in situ)
COMP519 Web Programming Lecture 17 Slide L17 11
Event-driven Programs Introduction
Event Handlers and HTML Elements
HTML events are things, mostly user actions,
that happen to HTML elements
Event handlers are JavaScript functions that process events
Event handlers must be associated with HTML elements
for specific events
This can be done via attributes
< input type =" button " value =" Help " onclic k =" Help ()" >
Alternatively, a JavaScript function can be used to add a handler to an
HTML element
// All good brows ers
window . add Eve ntL ist ener (" load " , Hello )
// MS IE brows er
window . a ttac hEve nt (" onload ", Hello )
More than one event handler can be added this way to the same
element for the same event or different events
COMP519 Web Programming Lecture 17 Slide L17 12
Event-driven Programs Introduction
Event Handlers and HTML Elements
As our scripts should work with as many browsers as possible,
we need to detect which method works:
if ( windo w . ad dEv ent Lis tener ) {
window . add Eve ntL ist ener (" load " , Hello )
} else {
window . a ttac hEve nt (" onload ", Hello )
}
Event handlers can also be removed
if ( windo w . re mov eEv ent Li ste ner ) {
window . rem ove Eve nt Lis ten er (" load ", Hello )
} else {
window . d etac hEve nt (" onload ", Hello )
}
COMP519 Web Programming Lecture 17 Slide L17 13
Event-driven Programs Introduction
Events: Load
An (on)load event occurs when an object has been loaded
Typically, event handlers for onload events are associated with the
window object or the body element of an HTML document
<! DO CTYPE html >
< html lang =" en - GB ">
<head >
<title > Onload Example </ title >
<script >
funct ion Hello () { alert (" Welcom e to my page !") }
</ script >
</ head >
< body on load =" Hello ()" >
<p > Conte nt of the web page </ p >
</ body >
</ html >
http://cgi.csc.liv.ac.uk/
~
ullrich/COMP519/examples/jsOnload.html
COMP519 Web Programming Lecture 17 Slide L17 14
Event-driven Programs Events
Events: Focus / Change
A focus event occurs when a form field receives input focus by tabbing
with the keyboard or clicking with the mouse
; onFocus attribute
A change event occurs when a select, text, or textarea field loses focus
and its value has been modified
; onChange attribute
Example:
< form name =" form1 " method =" post " actio n =" pr ocess . php ">
< select name =" select " requi red
onCha nge =" docu ment . form1 . submit ();" >
< option value ="" > Selec t a name </ option >
< option value ="20 0812345" > Tom Beck </ option >
< option value ="20 0867890" > Jim Kent </ option >
</ select >
</ form >
COMP519 Web Programming Lecture 17 Slide L17 15
Event-driven Programs Events
Events: Focus / Change
A focus event occurs when a form field receives input focus by tabbing
with the keyboard or clicking with the mouse
; onFocus attribute
A change event occurs when a select, text, or textarea field loses focus
and its value has been modified
; onChange attribute
<form >
<label > Te mper atur e in F ahre nhei t : </ label >
< input type =" text " id =" fa hrenheit " size ="10" value ="0"
oncha nge =" docu ment . get Elem ent ByI d ( ' celsius ' ). value =
Fah ren he itT oCe lsi us ( pars eFlo at (
docum ent . g etE lem entB yId ( ' fahrenheit ' ). value )). toFixed (1);"
><br >
<label > Te mper atur e in C elsius : </ label >
< input type =" text " id =" cels ius "
size ="10" value ="" onfoc us =" blur ();" > </ form >
http://cgi.csc.liv.ac.uk/
~
ullrich/COMP519/examples/jsOnchange.html
COMP519 Web Programming Lecture 17 Slide L17 16
Event-driven Programs Events
Events: Blur / Click
A blur event occurs when an HTML element loses focus
; onBlur attribute
A click event occurs when an object on a form is clicked
; onClick attribute
Example:
<html >< head > < title > Oncli ck Example </ title > </ head >< body >
< form name =" form1 " action ="" >
Enter a number here :
< input type =" text " size ="12" id =" number " value ="3.1" >
<br >< br >
< input type =" button " value =" Double "
onclic k =" d ocumen t . ge tEl emen tBy Id (' number ' ). value =
pars eFlo at ( do cument . ge tEle men tBy Id (' number ' ). value )
* 2;" >
</ form ></ body > </ html >
http://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/jsOnclick.html
COMP519 Web Programming Lecture 17 Slide L17 17
Event-driven Programs Events
Events: MouseOver / Select / Submit
A keydown event occurs when the user presses a key
; onkeydown attribute
A mouseOver event occurs once each time the mouse pointer moves
over an HTML element from outside that element
; onMouseOver attribute
A select event occurs when a user selects some of the text within a text
or textarea field
; onSelect attribute
A submit event occurs when a user submits a form
; onSubmit attribute
COMP519 Web Programming Lecture 17 Slide L17 18
Event-driven Programs Events
Events and DOM
When an event occurs, an event object is created
; an event object has attributes and methods
; event objects can be created by your code
independent of an event occurring
In most browsers, the event object is passed to event handler functions
as an argument
In most versions of Microsoft Internet Explorer, the most recent event
can only be accessed via window.event
<html >< body onKe yDown =" proc essK ey ( event )" >
<script >
funct ion p roce ssKey ( e) {
e = e || window . even t
docum ent . g etE lem entB yId (" m essage "). innerHTM L =
String . f rom Char Code ( e. keyCo de )+ ' has been pressed ' }
</ script >
<!- - key code will appear in the pa ragra ph below -- >
<p id =" messag e " > </ p >
</ body ></ html >
COMP519 Web Programming Lecture 17 Slide L17 19
Extended Example
Example: Two-Player Board Game
We want to develop a two-player board game
along the lines of Tic-Tac-Toe
The full code is available at
http://cgi.csc.liv.ac.uk/
~
ullrich/COMP519/examples/jsBoard.html
The interface will consist of a 3x3 table representing the board and a
section for messages, both of which will be generated dynamically
<body >
< table id =" t1 " > </ table >
<div id =" m1 " > </ div >
<script >... </ script >
</ body >
COMP519 Web Programming Lecture 17 Slide L17 20
Extended Example
Example: Two-Player Board Game
Following the Model-View-Controller paradigm we need a model of the
game, including the board and overall state of the
var board = [[0 ,0 ,0] ,[0 ,0 ,0] ,[0 ,0 ,0]];
var free = 9; // free posi tions on the board
var turn = 1; // al tern ates betwee n 0 and 1
We will use 0 to represent an empty position on the board
1 to represent a position taken by player 1
2 to represent a position taken by player 2
We have a function that turns these values into ‘nice’ representations
funct ion n umTo Lett er ( num ) {
switch ( num ) {
case 0: retur n " "
case 1: retur n " O"
case 2: retur n " X"
}
}
COMP519 Web Programming Lecture 17 Slide L17 21
Extended Example
Example: Two-Player Board Game
We need a function to show a message to the user
and another to clear that message
funct ion s howM essa ge ( message , style ) {
m1 = docum ent . g etE leme ntB yId (" m1 ");
m1 . inn erHTM L = message ;
m1 . style . displ ay = " block ";
m1 . cla ssNam e = s ty le ;
}
funct ion c lea rMes sage () {
m1 = docum ent . g etE leme ntB yId (" m1 ");
m1 . style . displ ay = " none ";
}
COMP519 Web Programming Lecture 17 Slide L17 22
Extended Example
Example: Two-Player Board Game
The play function implements the turn of a user
funct ion play (x ,y , event ) {
cle arMe ssag e ();
consol e . log (" x = " + x + " y = " + y );
consol e . log (" b = " + board [ y ][ x ]);
if ( board [y ][ x] > 0) {
showMes sage (" Grid pos ition [" + x + " ," + y +
"] alrea dy occ upied " ," Red BG ");
} else {
board [ y ][ x ] = 2 - turn ;
free --;
event . target . inner HTML = numT oLet ter (2 - turn );
turn = 1 - turn ;
}
}
Arguments x and y are the co-ordinates on which the player as placed a piece
event is the event that was triggered and event.target gives us the
HTML element / table cell on which it was triggered
COMP519 Web Programming Lecture 17 Slide L17 23
Extended Example
Example: Two-Player Board Game
At the start we create a representation of the board
funct ion init ( table ) {
for (j =0; j < board . length ; j ++) {
var tr = do cumen t . cr eate Ele ment (" tr ");
table . ap pend Chil d ( tr );
for (i =0; i < board [ j ]. l ength ; x ++) {
var td = doc ument . cre ate Elem ent (" td ");
var txt = doc ument . cre ate Tex tNod e (
numToLe tter ( board [ j ][ i ]);
td . ap pend Chil d ( txt );
td . se tAtt ribu te (' id ' ,"" + x + y );
td . ad dEv ent Lis ten er (" click " , play . bind ( null ,i , j ));
tr . ap pend Chil d ( td );
} } }
table = docum ent . g etE leme ntB yId ( ' t1 ' );
init ( table );
play.bind makes sure that parameters x and y of play are bound to the
current values of i and j
COMP519 Web Programming Lecture 17 Slide L17 24
Extended Example
Example: Two-Player Board Game
Finally, we add some CSS directives to improve the visual appearance
of the game
<style >
td { border : 1 px solid black ;
width : 2 em ;
height : 2 em ;
text - align : center ;
vertical - align : middle ;
}
div . RedBG {
background - color : # f00 ;
}
div . Gre enBG {
background - color : #0 f0 ;
}
</ style >
COMP519 Web Programming Lecture 17 Slide L17 25
Extended Example
Example: Adding a Computer Player / Delays
var p roces sing = false
async fun ction play (x ,y , event ) {
if (! pro cess ing ) {
proc essi ng = true ;
cle arMe ssag e ();
if ( board [y ][ x] > 0) {
showMes sage (" Grid pos ition [" + x + " ," + y +
"] alrea dy occ upied " ," Red BG ");
} else {
board [ y ][ x ] = 2 - turn ; free - -;
event . target . inner HTML = numT oLet ter (2 - turn );
turn = 1 - turn ;
await sleep ( 250); // sleep 250 ms
com pute rMov e ();
proc essi ng = false
} } }
funct ion sleep ( ms ) {
return new Pr omise ( resolve = > setT imeo ut ( resolve , ms )) }
COMP519 Web Programming Lecture 17 Slide L17 26
Extended Example
Example: Two-Player Board Game
Possible improvements:
We should detect that the board is full (free == 0) and
end the game with an appropriate message
We should detect a winning placement of pieces on the board,
end the game and declare a winner
If we have a computer player, then we need to implement
computerMove
COMP519 Web Programming Lecture 17 Slide L17 27
Further Reading
Revision and Further Reading
Read
Chapter 21: Introduction to JavaScript: Events
Chapter 22: Using JavaScript: Meet the DOM
of J. Niederst Robbins: Learning Web Design: A Beginner’s
Guide to HTML, CSS, JavaScript, and Web Graphics (5th ed).
O’Reilly, 2018.
E-book https://library.liv.ac.uk/record=b5647021
Read
Chapter 10: The Document Object Model
Chapter 12: Events
of N. C. Zakas: Professional JavaScript for Web developers.
Wrox Press, 2009.
Harold Cohen Library 518.59.Z21 or
E-book http://library.liv.ac.uk/record=b2238913
COMP519 Web Programming Lecture 17 Slide L17 28