COMP284 Scripting Languages
Lecture 17: JavaScript (Part 4)
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
Window and Document objects
Window object: Properties and methods
Dialog boxes
Input validation
Document object and Document Object Model
COMP284 Scripting Languages Lecture 17 Slide L17 1
Dynamic web pages using JavaScript Window and Document objects
Window and Document objects
JavaScript provides two objects that are essential to the creation of
dynamic web pages and interactive web applications:
window object
a JavaScript object that represents a browser window or tab
automatically created whith every instance of a <body> or
<frameset> tag
allows properties of a window to be accessed and manipulated
; JavaScript provides methods that allow window objects to be
created and manipulated
Example: window.open(’http://www.csc.liv.ac.uk’,’Home’)
whenever an object method or property is referenced in a script without
an object name and dot prefix it is assumed by JavaScript to be a
member of the window object
Example: We can write alert() instead of window.alert()
COMP284 Scripting Languages Lecture 17 Slide L17 2
Dynamic web pages using JavaScript Window object: Properties and methods
Window object
A window object represents an open window in a browser.
If a document contain frames, then there is
one window object, window, for the HTML document
and one additional window object for each frame,
accessible via an array window.frames
A window object has properties including
document document object for the window
history history object for the window
location location object (current URL) for the window
navigator navigator (web browser) object for the window
opener reference to the window that created the window
innerHeight inner height of a window’s content area
innerWidth inner width of a window’s content area
closed boolean value indicating whether the window is
(still) open
COMP284 Scripting Languages Lecture 17 Slide L17 3
Dynamic web pages using JavaScript Window object: Properties and methods
Navigator object
Properties of a navigator object include
navigator.appName the web brower’s name
navigator.appVersion the web brower’s version
Example: Load different style sheets depending on browser
<! DOCTYPE html >
<html >< head >< title > Naviga t o r example </ title >
< script type =" text / javasc r ipt " >
if ( na v iga t o r . appName == ' Netscape ' ) {
document . writeln ( ' < link rel = styles h eet type =" text /css " ' +
href =" Ne t s c a pe . css " >' )
} else if ( navi g a tor . appName == ' Opera ' ) {
document . writeln ( ' < link rel = styles h eet type =" text /css " ' +
href =" Opera . css ">' )
} else {
document . writeln ( ' < link rel = styles h eet type =" text /css " ' +
href =" Others . css "> ' )
}
</ script > </ head >< body > ... </ body > </ html >
COMP284 Scripting Languages Lecture 17 Slide L17 4
Dynamic web pages using JavaScript Window object: Properties and methods
Window object
Methods provided by a window object include
open(url, name [, features])
opens a new browser window/tab
returns a reference to a window object
url is the URL to access in the new window; can be the empty string
name is a name given to the window for later reference
features is a string that determines various window features
The standard sequence for the creation of a new windows is not:
// new instance of ` Window ' class
var newWin = new Wi ndow (...)
newWin . document . write ( ' <html >... </ html > ' )
instead it is
// new wi ndow created by using ` open ' with an existing one
var newWin = window . open (...)
newWin . document . write ( ' <html >... </ html > ' )
COMP284 Scripting Languages Lecture 17 Slide L17 5
Dynamic web pages using JavaScript Window object: Properties and methods
Window object
Methods provided by a window object include
close()
closes a browser window/tab
focus()
give focus to a window (bring the window to the front)
blur()
removes focus from a window (moves the window behind others)
print()
prints (sends to a printer) the contents of the current window
COMP284 Scripting Languages Lecture 17 Slide L17 6
Dynamic web pages using JavaScript Window object: Properties and methods
Window object: Example
< html lang = "en - GB ">< head >< title > Wind ow handling </ title >
< script type =" text / javasc r ipt " >
function Help () {
var OutputWi n do w = win dow . open ( ' ' , ' Help ' , ' resiza b le =1 ' );
with ( Output W in d ow . document ) {
open ()
writeln (" <! DOCTYPE html > < html >< head > <title > Help </ title >\
</ head >< body > This might be a context - s e n sit i v e help \
message , de pen d i ng on the ap p li c at i on and state of the
page . </ body > </ html > ");
close ()
}
}
</ script > </ head > <body >
< form name = " Bu t to n F or m " id =" ButtonF o r m " action ="" >
<p >
< input type = " b u tton " value =" Click for Help "
onclick =" Help (); " >
</p >
</ form > </ body > </ html >
COMP284 Scripting Languages Lecture 17 Slide L17 7
Dynamic web pages using JavaScript Dialog boxes
Window object: Dialog boxes
Often we only want to open a new window in order to
display a message
ask for confirmation of an action
request an input
For these purposes, the window object in JavaScript provides
pre-defined methods for the handling of dialog boxes
(windows for simple dialogs):
null alert(message_string)
bool confirm(message_string)
string prompt(message_string, default)
COMP284 Scripting Languages Lecture 17 Slide L17 8
Dynamic web pages using JavaScript Dialog boxes
Window object: Dialog boxes
null alert(message_string)
creates a message box displaying message_string
the box contains an ‘OK’ button that the user will have to click
(alternatively, the message box can be closed)
for the execution of the remaining code to proceed
Example:
alert ( " Local time : " + ( new Date ). toStri n g ())
COMP284 Scripting Languages Lecture 17 Slide L17 9
Dynamic web pages using JavaScript Dialog boxes
Window object: Dialog boxes
bool confirm(message_string)
creates a message box displaying message_string
the box contains two buttons ‘Cancel’ and ‘OK’
the function returns true if the user selects ‘OK’, false otherwise
Example:
var answer = confirm ( "Are you sure ? " )
COMP284 Scripting Languages Lecture 17 Slide L17 10
Dynamic web pages using JavaScript Dialog boxes
Window object: Dialog boxes
string prompt(message_string, default)
creates a dialog box
displaying message_string
and an input field
if a second argument default
is given, default will be
shown in the input field
the box contains two buttons
‘Cancel’ and ‘OK’
if the user selects ‘OK’ then
the current value entered in
the input field is returned as a
string, otherwise null is
returned
Example:
var u s e rName =
prompt (" What is your name ?" ,
"" )
COMP284 Scripting Languages Lecture 17 Slide L17 11
Dynamic web pages using JavaScript Dialog boxes
Window object: Dialog boxes
prompt() always returns a string, even if the user enters a number
To convert a string to number the following functions can be used:
number parseInt(string [,base])
converts string to an integer number wrt numeral system base
only converts up to the first invalid character in string
if the first non-whitespace character in string is not a digit, returns NaN
number parseFloat(string)
converts string to a floating-point number
only converts up to the first invalid character in string
if the first non-whitespace character in string is not a digit, returns NaN
number Number(string)
returns NaN if string contains an invalid character
COMP284 Scripting Languages Lecture 17 Slide L17 12
Dynamic web pages using JavaScript Dialog boxes
Dialog boxes: Example
<! DOCTYPE html >
< html lang = "en - GB ">
<head >< title > Int e r ac t io n example </ title > </ head >
<body >
< script type =" text / javasc r ipt " >
do {
string = pr ompt ( " How many items do you want to buy ?")
quantity = p a r s eInt ( string )
} while ( isNaN ( quantity ) || quantity <= 0)
do {
string = prompt ( " How much does an item cost ?")
price = parseFloat ( string )
} while ( isNaN ( price ) || price <= 0)
buy = confirm (" You will have to pay " +
( price * quantity ). toFixed (2)+
"\ nDo you want to proceed ? " )
if ( buy ) alert (" Purc h a s e made ")
</ script >
</ body > </ html >
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/jsPrompt.html
COMP284 Scripting Languages Lecture 17 Slide L17 13
Dynamic web pages using JavaScript Input validation
User input validation
A common use of JavaScript is the validation of user input
in a HTML form before it is processed:
check that required fields have not been left empty
check that fields only contain allowed characters or
comply to a certain grammar
check that values are within allowed bounds
< form method =" post " acti on =" process . php "
onS ubmi t =" return v alid ate ( this )" >
<label > User name : < input type =" text " name =" user " ></ label >
<label > Email address : < input type = " text " name =" email " ></ label >
< input type =" su bmit " name =" s ubmit ">
</ form >
<script >
fun ctio n va lidat e ( form ) {
fail = va l idateU s er ( form . user . val ue )
fail += vali d ateEma i l ( form . email . value )
if ( fail == " " ) re turn true
else { al ert ( fail ); ret urn false } }
</ script >
COMP284 Scripting Languages Lecture 17 Slide L17 14
Dynamic web pages using JavaScript Input validation
User input validation
1 function valida t eU s er ( field ) {
2 if ( field == " ") return "No usern a m e e n t e r e d \ n"
3 else if ( field . length < 5)
4 return " Userna m e too short \ n"
5 else if (/[^ a- zA -Z0 -9 _ -]/. test ( field ))
6 return " Invalid char a c ter in username \n "
7 else return " "
8 }
9
10 function valida t eE ma il ( field ) {
11 if ( field == " ") return "No email entered \n "
12 else if (!(( field . in d e x O f ( ".") > 0) &&
13 ( field . indexOf (" @") > 0)) ||
14 /[^ a- zA -Z0 -9. @_ -]/. test ( field ))
15 return " Invalid char a c ter in email \n "
16 else return " "
17 }
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/jsValidate.html
COMP284 Scripting Languages Lecture 17 Slide L17 15
Dynamic web pages using JavaScript Input validation
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
COMP284 Scripting Languages Lecture 17 Slide L17 16
Dynamic web pages using JavaScript Document object and Document Object Model
Document Object Model
Example:
The HTML table below
<table >
<tbody >
<tr >
<td > Sh ady Grove </ td >
<td > Aeo lian </ 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]
COMP284 Scripting Languages Lecture 17 Slide L17 17
Dynamic web pages using JavaScript Document object and Document Object Model
Accessing HTML elements: Object methods
Example:
// a ccess the t body el em en t from the table element
var myT bod yE lem ent = my Tab leE le men t . first Child ;
// a ccess its s ec on d tr elem en t ; the list of child re n starts at 0 ( not 1).
var myS eco ndT rEl eme nt = myT bod yEl eme nt . c hildN odes [1];
// r emove its f irst td el ement
my S ec o nd TrE lem ent . r emo ve Chi ld ( my Sec ond TrE le m en t . fir stChi ld );
// c hange the text content of the re maini ng td ele ment
my S ec o nd TrE lem ent . f irs tC hild . fi rs tCh il d .dat a = " Pet er ";
COMP284 Scripting Languages Lecture 17 Slide L17 18
Dynamic web pages using JavaScript Document object and Document Object Model
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 a HTML element
Example:
< form name =" form1 " a ctio n ="" >
<label > Tempera t ure in Fahr e nheit :</ label >
< input type =" text " name =" fahrenh e it " size =" 10 " value ="0" ><br >
<label > Tempera t ure in Cel sius : </ label >
< input type =" text " name =" celsius "
size = " 10 " val ue =" " >
</ form >
Then document.form1
Refers to the whole form
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
COMP284 Scripting Languages Lecture 17 Slide L17 19
Dynamic web pages using JavaScript Document object and Document Object Model
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 " a ctio n ="" >
<div clas s =" field " name =" fdiv ">
<label > Tempera t ure in Fahr e nheit :</ label >
< input type =" text " name =" fa h renhei t " size =10 val ue =" 0 " />
</div >
<div clas s =" field " name =" cdiv ">
<label > Tempera t ure in Cel sius : </ label >
< input type =" text " name =" celsius " size = " 10 " val ue =" " />
</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
COMP284 Scripting Languages Lecture 17 Slide L17 20
Dynamic web pages using JavaScript Document object and Document Object Model
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
a HTML element by its ID
Example:
< form id =" form 1 " actio n ="" >
<label > Tempera t ure in Fahr e nheit :</ label >
< input type =" text " id =" fahren h eit " size =" 10" va lue =" 0 " ><br >
<label > Tempera t ure in Cel sius : </ label >
< input type =" text " id =" c elsius "
size = " 10 " val ue =" " >
</ 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
COMP284 Scripting Languages Lecture 17 Slide L17 21
Dynamic web pages using JavaScript Document object and Document Object Model
Manipulating HTML elements
It is not only possible to access HTML elements, but also possible to
change them on-the-fly
<! D OCT YPE html >
< html lang = " en - GB ">< head > < title > Man ipul a ting HTML elements </ title >
<style >
td . RedBG { b ack grou nd : # f00 ; }
</ style >
<script >
fu nction ch a ngeBa ckgro u nd1 (id ) {
do cument . getE l emen tByI d ( id ). style . back gro u nd = " #00 f" ;
do cument . getE l emen tByI d ( id ). in nerH TML = " blue " ;
}
fu nction ch a ngeBa ckgro u nd2 (id ) {
do cument . getE l emen tByI d ( id ). cell . clas sNa me = " RedBG ";
do cument . getE l emen tByI d ( id ). cell . inne rHT ML = "red " ;
}
</ script > </ head > < body >
< table border ="1 " ><tr >
<td id =" 0 " onclic k =" c h angeB ackgr o und1 ( ' 0 ' ); " >white </ td >
<td id =" 1 " onclic k =" c h angeB ackgr o und2 ( ' 1 ' ); " >white </ td >
</tr ></ table > </ body > </ html >
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/jsBG.html
COMP284 Scripting Languages Lecture 17 Slide L17 22
Dynamic web pages using JavaScript Document object and Document Object Model
Revision
Read
Chapter 17: JavaScript and PHP Validation and Error Handling
of
R. Nixon:
Learning PHP, MySQL, and JavaScript.
O’Reilly, 2009.
Mozilla Developer Network and individual contributors:
Document Object Model (DOM), 18 March 2014.
https://developer.mozilla.org/en/docs/DOM
[accessed 18 March 2014].
W3Schools: JavaScript and HTML DOM Reference,
18 March 2014. http://www.w3schools.com/jsref/
[accessed 18 March 2014].
COMP284 Scripting Languages Lecture 17 Slide L17 23