COMP284 Scripting Languages
Lecture 13: 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 13 Slide L13 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 13 Slide L13 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 13 Slide L13 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 13 Slide L13 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 13 Slide L13 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 13 Slide L13 6
Dynamic web pages using JavaScript Window object: Properties and methods
Window object: Example
< html lang = ' en - GB ' >< head >< title > Wind o w handling </ title >
< script type =' text / javasc r ipt ' >
function Help () {
var OutputWi n do w = win dow . open ( ' ' , ' Help ' , ' resiza b le =1 ' );
Outpu t Wi n do w . docu m e n t .open ()
Outpu t Wi n do w . docu m e n t . writeln ( " <! DOCTYPE html >\
< html lang = ' en - GB ' >< 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 > ");
Outpu t Wi n do w . docu m e n t .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 13 Slide L13 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 13 Slide L13 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 ). toString ())
COMP284 Scripting Languages Lecture 13 Slide L13 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 13 Slide L13 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 13 Slide L13 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
Apply an identity function of number, for example, string * 1
Note: Conversion may return a number even if string is not
(for example, 2014Mar)
COMP284 Scripting Languages Lecture 13 Slide L13 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 >
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 13 Slide L13 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 m ethod =" post " action =" pro cess . php "
onSu b mit =" re turn validate ( this )" >
<label > User name : < input type = " text " name =" user " ></ label >
<label > Email addres s : < input type =" text " name =" email " ></ label >
< input type = " submit " name =" submit ">
</ form >
<script >
func t ion v a lidate ( form ) {
fail = va l i d a teUser ( form . user . valu e )
fail += validateEmail ( form . email . value )
if ( fail == "" ) return true
else { alert (fail ); return false } }
</ script >
COMP284 Scripting Languages Lecture 13 Slide L13 14
Dynamic web pages using JavaScript Input validation
User input validation
function valida t eU se r ( field ) {
if ( field == " ") return "No username entered \n"
else if ( field . length < 5)
return " Userna m e too short \n"
else if ( field . match (/[^a -zA - Z0 -9_ -]/))
return " Invalid character in username \ n "
else re t urn ""
}
function valid a te Em a il ( field ) {
if ( field == " " ) return " No email entered \n "
else if (!(( field . indexOf (" . ") > 0) &&
( field . indexOf (" @") > 0)))
return " Invalid forma t of email \ n "
else if ( field . match (/[^a -zA - Z0 -9. @_ -]/))
return " Invalid character in ema il \ n "
else re t urn ""
}
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/jsValidate.html
COMP284 Scripting Languages Lecture 13 Slide L13 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 13 Slide L13 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 13 Slide L13 17
Dynamic web pages using JavaScript Document object and Document Object Model
Accessing HTML elements: Object methods
Example:
// acce ss the tb od y eleme nt fro m the table e lement
var myTb odyE lem ent = my Tab leEl eme nt . firstChi ld ;
// acce ss its second tr elemen t ; the list of child ren sta rt s at 0 ( not 1).
var mySec ond T rEl emen t = m yTbo dyE lem ent . ch ild Nod es [1];
// remo ve its fi rs t td elem en t
myS eco n dTr Ele m ent . remo veC hil d ( mySe con d TrE leme nt . fi rst Chi ld );
// chan ge the text con tent of the rem ain ing td eleme nt
myS eco n dTr Ele m ent . firstC hil d . fir stC hil d . data = " Pe te r " ;
COMP284 Scripting Languages Lecture 13 Slide L13 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 " ac tion =" " >
<label > Tempera t u r e in Fahrenheit : </ label >
< i nput type =" text " name =" fahrenheit " size =" 10 " value ="0" ><br >
<label > Tempera t u r e in Celsius : </ label >
< i nput type =" text " name =" ce l sius " size =" 10 " value ="" >
</ 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 13 Slide L13 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 " ac tion =" " >
<div class =" field " name =" fdiv ">
<label > Tempera t u r e in Fahrenheit : </ label >
< i nput type =" text " name =" fahrenheit " size =10 value ="0 ">
</div >
<div class =" field " name =" cdiv ">
<label > Tempera t u r e in Celsius : </ label >
< i nput type =" text " name =" ce l sius " size =" 10 " value ="" >
</div >
</ form >
; there is now a div element between form and text field
; document.form1.celsius no longer works
; we now need to use document.form1.cdiv.celsius
COMP284 Scripting Languages Lecture 13 Slide L13 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 =" form1 " action ="" >
<label > Tempera t u r e in Fahrenheit : </ label >
< i nput type =" text " id= " f a h r e nheit " size = " 10 " value ="0 " ><br >
<label > Tempera t u r e in Celsius : </ label >
< i nput type =" text " id= " celsius " size =" 10 " value ="" >
</ 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 13 Slide L13 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 ). cl assN ame = " RedBG " ;
do cument . getE l emen tByI d ( id ). in nerH TML = " 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 13 Slide L13 22
Dynamic web pages using JavaScript Document object and Document Object Model
Revision
Read
Chapter 16: JavaScript and PHP Validation and Error Handling
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 13 Slide L13 23