COMP284 Scripting Languages
Lecture 14: JavaScript (Part 5)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
1 Event-driven Programs
Introduction
Events
2 Extended Example
3 What next?
COMP284 Scripting Languages Lecture 14 Slide L14 1
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
COMP284 Scripting Languages Lecture 14 Slide L14 2
Event-driven Programs Introduction
Event-Driven JavaScript Programs
Client-side 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)
COMP284 Scripting Languages Lecture 14 Slide L14 3
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 " onclick =" Help () " >
Alternatively, a JavaScript function can be used to add a handler to an
HTML element
// All good brows ers
window . a ddE ven tLi s ten er (" load " , Hello )
// MS IE browser
window . at tach Even t ( " onload " , Hello )
More than one event handler can be added this way to the same
element for the same event
COMP284 Scripting Languages Lecture 14 Slide L14 4
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 ( window . ad dEv ent Lis ten er ) {
window . a ddE ven tLi s ten er (" load " , Hello )
} else {
window . a t tach Even t ( " onload " , Hello )
}
Event handlers can also be removed
if ( window . re mo v eE ven tLi ste ner ) {
window . r emo veE ven tL i st ene r ( " load " , Hello )
} else {
window . d e tach Even t ( " onload " , Hello )
}
COMP284 Scripting Languages Lecture 14 Slide L14 5
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
< html lang = "en - GB " >
<head >
<title > Onload Example </ title >
< script type = " text / jav ascri pt " >
functi on Hello () { alert ( " Welcome to my page ! ") }
</ script >
</ head >
< body o n load = " Hello () " >
<p > Content of the web page </p >
</ body >
</ html >
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/jsOnload.html
COMP284 Scripting Languages Lecture 14 Slide L14 6
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 name = " form1 " method =" post " action =" process . php " >
< select name = " sel ect " require d
onChan ge = " docume n t . form1 . submit (); " >
< option value =" " > Select a name </ option >
< option value =" 20081 2345 " > Tom Beck </ option >
< option value =" 20086 7890 " > Jim Kent </ option >
</ select >
</ form >
COMP284 Scripting Languages Lecture 14 Slide L14 7
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 > Tem pera ture in Fahre nhei t : </ label >
< input type =" text " id =" fahr enhe it " size =" 10 " value = "0 "
onchan ge = " docume n t . ge tEl emen tBy Id (' celsius ' ). value =
Fah ren hei tTo Ce lsi us ( p arse Float (
docume nt . g e tEl eme ntBy Id (' fah r enhe it ' ). value )). toFixe d (1); "
>
<label > Tem pera ture in Celsius : </ label >
< input type =" text " id =" celsius "
size =" 10 " value = "" onfocus =" blur (); " > </ form >
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/jsOnchange.html
COMP284 Scripting Languages Lecture 14 Slide L14 8
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
<! D O CTYPE html >
<html >< head >< title > Onclick Example </ title > </ head >< body >
< form name = " form1 " action =" " >
Enter a numbe r here :
< input type =" text " size =" 12 " id =" number " value = " 3.1 " >
< input type =" button " value = " Doub le "
onclick =" docu ment . g etE lem entB yId ( ' number ' ). value =
pars eFloa t ( docu ment . g etE lem entB yId ( ' number ' ). value )
* 2; " >
</ form ></ body > </ html >
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/jsOnclick.html
COMP284 Scripting Languages Lecture 14 Slide L14 9
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
COMP284 Scripting Languages Lecture 14 Slide L14 10
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 o nKeyD own =" proc essKe y ( event ) " >
<script >
functi on p roces sKey (e ) {
e = e || window . event
docume nt . g e tEl eme ntBy Id (" key " ). inne rHTML =
String . f romC harC ode (e . k eyCode )+ ' has been pre s sed ' }
</ script >
<!- - key code will a ppear in the par agrap h below -->
<p id =" key " > </p >
</ body ></ html >
COMP284 Scripting Languages Lecture 14 Slide L14 11
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
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/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 >
COMP284 Scripting Languages Lecture 14 Slide L14 12
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 terna tes between 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
functi on n umTo Lett er ( num ) {
switch ( num ) {
case 0: return " "
case 1: return "O "
case 2: return "X "
}
}
COMP284 Scripting Languages Lecture 14 Slide L14 13
Extended Example
Example: Two-Player Board Game
We need a function to show a message to the user
and another to clear that message
functi on s howM essa ge ( message , style ) {
m1 = d ocumen t . ge t Ele men tByI d (" m1 " );
m1 . inne rHTML = mess age ;
m1 . style . display = " block ";
m1 . clas sName = style ;
}
functi on c lear Mess age () {
m1 = d ocumen t . ge t Ele men tByI d (" m1 " );
m1 . style . display = " none " ;
}
COMP284 Scripting Languages Lecture 14 Slide L14 14
Extended Example
Example: Two-Player Board Game
The play function implements the turn of a user
functi on play (x ,y , event ) {
clea rMe ssag e ();
console . log (" x = "+ x+ " y = "+ y ); // deb ugging
console . log (" b = "+ board [ y ][ x ]); // debu gging
if ( board [y ][ x] > 0) {
show Mess age (" Grid po sition [ "+ x+ " ,"+ y+
"] al ready oc cupied " ," RedBG " );
} else {
board [ y ][ x ] = 2- turn ;
free --;
event . target . in nerHTM L = numTo Lett er (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
COMP284 Scripting Languages Lecture 14 Slide L14 15
Extended Example
Example: Two-Player Board Game
At the start we create a representation of the board
functi on init ( table ) {
for ( j =0; j < board . le ngth ; j ++) {
var tr = do cument . cre a teE leme nt (" tr " );
table . app endC h ild ( tr );
for ( i =0; i < board [j ]. length ; x ++) {
var td = documen t . cre ateE lem ent (" td " );
var txt = docume nt . cr eat eTe xtNo de (
numT oLet ter ( board [j ][ i ]);
td . app endC hild ( txt );
td . ad dEv ent List ene r (" c lick " , play . bind ( null ,i ,j ));
tr . app endC hild ( td );
}
}
}
table = do cument . get Elem ent ByI d ( ' t1 ' );
init ( table );
play.bind makes sure that parameters x and y of play are bound to the
current values of i and j
COMP284 Scripting Languages Lecture 14 Slide L14 16
Extended Example
Example: Two-Player Board Game
Finally, we add some CSS directives to improve the visual appearance
of the game
<style >
td { bord er : 1 px solid black ;
width : 2 em ;
height : 2em ;
text - align : center ;
vertical - align : middle ;
}
div . RedBG {
background - color : # f00 ;
}
div . Green BG {
background - color : # 0 f0 ;
}
</ style >
COMP284 Scripting Languages Lecture 14 Slide L14 17
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
COMP284 Scripting Languages Lecture 14 Slide L14 18
What next?
What next?
Web applications almost always combine
client-side scripting and server-side scripting
; How to connect to a server using JavaScript?
Ajax (Asynchronous JavaScript and XML) is a
set of techniques for sending and retrieving data
from a server (asynchronously)
On the server-side often a PHP script acts as
mediator that retrieves data from a database in
response to Ajax requests
Data is typically exchanged in XML or JSON
(JavaScript Object Notation) format
By DanielSHaischt,
via Wikimedia Commons
https://commons.wikimedia.org/wiki/File%3AAjax-vergleich.svg,
CC BY-SA 3.0,
https://commons.wikimedia.org/w/index.php?curid=29724785
COMP284 Scripting Languages Lecture 14 Slide L14 19
What next?
What next?
Development of applications typically does not start from scratch
; modules and libraries / frameworks are used
PHP frameworks
Laravel
CodeIgniter
Symfony
CakePHP
Zend Framework
Phalcon
FuelPHP
PHPPixie
JavaScript frameworks
jQuery
Angular (Google)
React (Facebook)
Vue.js
Ember.js
Node.js
Mithril
Polymer
Using a framework is a skill in itself
Popularity / use of frameworks changes quite frequently
; not clear which ones to teach / learn
COMP284 Scripting Languages Lecture 14 Slide L14 20
What next?
Revision
Read
Chapter 17: Using Asynchronous Communication
of
R. Nixon: Learning PHP, MySQL & JavaScript:
with jQuery, CSS & HTML5. O’Reilly, 2018.
Mozilla Developer Network and individual contributors:
Document Object Model (DOM), 17 November 2019.
https://developer.mozilla.org/en/docs/DOM
[accessed 4 January 2020].
W3Schools: JavaScript and HTML DOM Reference,
4 January 2019. http://www.w3schools.com/jsref/
[accessed 4 January 2019].
COMP284 Scripting Languages Lecture 14 Slide L14 21