Title: CS230 Information Processing Section 3 Client Side Web Programming
1CS230 Information Processing Section 3
Client Side Web Programming
- 2004
- Mr Bart Busschots, BSc, AMInstP.
2Section 3.8
3Invoking JS
- There are many different ways to have your JS
called. - The simplest way is to call it from within a
script tag but this only happens once as the
document loads. - If you wish to call JS functions at other times
you must use event handelers. These call JS
functions when certain events are triggered on
the page either by the user or by the browser.
4JS Event Handelers
- onabort when the user aborts the loading of the
page element - onblur when the page element looses focus
- onclick when the user clicks on the page
element. If the page element performs some action
when clicked (e.g. a link) the action will only
happen if onclick returns true. - onchange when the user changes the content of
the page element. Only avaliable on some form
elements. - ondblclick when the user double clicks on the
page element (does not work on Macs) - onerror when there is an error loading the
document element (e.g. an image fails to load)
5JS Event Handelers
- onfocus when the page element gains focus
- onload when the page element finishes loading
- onmouseover when the mouse moves over the page
element - onmouseout when the mouse moves off the page
element - onsubmit when the form gets submitted. The form
will only submit if onsubmit returns true. - onunload when the page element is unloaded
(e.g. the user goes to another page or closes the
window)
6JS Event Handelers Example
-
- ltbody onloadwindow.alert(page is finished
loading) onunloadwindow.alert(sorry to see
you leave)gt - ltpgtyou can make lta hrefsomepage
onclickreturn window.confirm(Are you sure you
want to follow this link?)gtconditional
linkslt/agt using the onclick handeler. -
- ltimg srcsomething.jpg altan image
onerrorwindow.alert(Image Failed to load) /gt - lt/bodygt
- lt/htmlgt
7JS Timers
- There are two JS functions that allow you to time
function calls. - window.setTimeout(JS Code, n)
- Runs the JS code supplied once after n
milliseconds - E.g.
- setTimeout(window.alert(Time Up!), 10000)
- window.setInterval(JS Code, n)
- Same as setTimeout except the code continues to
execute every n millisceonds. - Returns a unique ID that can be passed to
window.clearInterval(id) at any point to stop the
interval.
8Variable Length Argument Lists
- Unlike in Java you do not have to specify the
amount of, or names of, all arguments a function
accepts when declaring it. - Instead of specifying names for arguments you can
access the values passed at run-time using the
arguments variable accesable within any function. - You can also use a hybrid of these two ways of
addressing arguments and name the required
arguments and then check the arguments variable
to see if any other optional arguments were
passed.
9Variable Length Arguments Lists
- Example
- function add(num1, num2)
- //add the named arguments
- this.ans num1 num2
- //add any un-named arguments
- for(this.i2this.iltarguments.lengththis.i)
- this.ans argumentsthis.i
-
- return this.ans
-
- var x add(3,4)
- var y add(x, 5, 6, 7)
10JavaScript REs
- Regular Expressions (REs) allow us to specify
patterns in text. - They can be used to
- search for patterns in text
- test if text contains a certain patern
- replace one pattern in text with another
- Break a string into sub parts based on a pattern
(e.g. break up a date into day, month and year) - JavaScript uses Perl Style Syntax to represent
REs.
11JavaScript REs
- You can declare an RE using a literal of the
following form - var myRE /ltpatterngt/ltmodifiersgt
- E.g.
- var x /and/i
- The above RE would try to match the string and
in any string ignoring the case. - To check if a string contains a pattern we can
use the test method. - if(x.test(this and that) true)
12RE Operators
- As well as matching simple strings, REs can match
more complex patters using the following
opperators - ? zero or one instances of
- one or more instances of
- zero or more instances of
- or
- These operators only apply to the character
directly to the left of the operator. You can
group larger patterns with brackets and then
apply the opperators to those groups.
13RE Special Characters
- There are also a number of special characters you
can use within regular expressions - . matches any character
- matches the start of a line
- matches the end of a line
- You can specify a set of characters to match
using You can invert the selection by starting
it with . - E.g. abc matches a OR b OR c and abc matches
any character except a, b or c. - You can also specify a range using
- E.g. 0-9 matches any digit
14RE Special Characters
- \w matches any word character (a-zA-Z0-9_)
- \d matches any digit (0-9)
- \b matches any white space ( \n\r\t)
- \W matches any non-word character
(a-zA-Z0-9_) - \D matches any non-digit character (0-9)
- You can also use \ to escape out characters that
would otherwise be interpreted as commands. E.g. - \/ matches a /
- \ matches a
- \. Matches a .
15RE Modifiers
- You will remember that RE literals take the
following form - /ltpatterngt/ltmodifiersgt
- You can use the following modifiers to manipulate
the behaviour of an RE - g global pattern matching
- i ignore case
- x ignore all white space within the patten that
is not expressly included (using \ )
16RE Sub-Patterns and Back-References
- You can use REs to break up a pattern into sub
patterns using brackets and the RegExp object. - E.g. if you want to split a URL up into its
component parts you would use an RE that looks
like this - /(\w)//(/)(\d)?( )/
- After the RE has been run the matched
sub-patterns can be found in the global RegExp
variable maintained by JS. The first sub-pattern
will be in RegExp.1, the second in RegExp.2 and
so on.
17JS RE Functions
- test()
- A function applied to a Regular Expression to
check if a string (passed as the first argument)
contains a match to the RE. - E.g.
- var myRE /and/i
- if(myRE.test(window.prompt(Enter a String to
test, )) true) - window.alert(The String did match the
pattern) - else
- window.alert(The String did not match the
pattern)
18JS RE Functions
- match()
- This function can be called on any string and is
used to extract sub-parts of the string based on
the pattern specified by the RE. - E.g.
- var time 1230
- time.match(/(\d\d)(\d\d)/)
- var hours RegExp.1
- var minutes RegExp.2
- You can pass an RE to the split() function
described in the previous section instead of a
string to split a string on a given pattern.
19JS RE Fucntions
- replace()
- This function can be applied to any string and
replaces all occurances of a given pattern in
that string with a given replacement. - E.g.
- var myString this that
- myString.replace(/\/g, amp)
- You can also refer to sub matches in the pattern
from within the replacement using 1, 2 . - E.g. the following example converts dates from EU
format to US format. - var myString 24-12-04
- myString.replace(/(\d\d)-(\d\d)-(\d\d)/g,
2-1-3)
20Object Oriented JS (NOT ON EXAM)
- JS implements OO in a rather unique way.
- JS OO is implemented using a data structure
refered to as a prototype. In very advanced JS
programming you manually manipulate these
prototypes. - In JS there are no such things as classes, you
create classes simply by writing one function
which in effect acts as the constructor for
objects of that class. - You use this function to add methods to your
class using function literals. - Because JS OO is so unique the best way to
illustrate the workings of objects is with some
examples.
21Simple JS OO Example
- //defining a lamp class
- function lamp()
- //declaring class variables
- this.state OFF
-
- //declaring functions
- this.turnOn function()
- this.state ON
-
- this.turnOff function()
- this.state OFF
-
- this.getState function()
- return this.state
-
22Simple JS OO Example
- //using our new lamp class
- //declaring a new lamp
- var myLamp new lamp()
- //calling functions on my new lamp
- window.alert(myLamp.getState())
- mylamp.turnOn()
- window.alert(myLamp.getState())
23Complex JS OO Example - Inheritance
- //create a new colouredLamp class that inherits
from lamp - function colouredLamp(c)
- //do the inheritance
- this.inherit lamp
- this.inherit()
- //declare aditional variables
- this.colour c
- //declare aditional functions
- this.setColour function(clr)
- this.colour clr
-
- this.getColour function()
- return this.colour
-
24Complex JS OO Example - Inheritance
- //using our new colouredLamp class
- //declaring a new coloured lamp
- var myLamp new colouredLamp(Red)
- //calling functions on my new lamp
- window.alert(myLamp.getState())
- window.alert(myLamp.getColour())
- mylamp.turnOn()
- myLamp.setColour(Blue)
- window.alert(myLamp.getState())
- window.alert(myLamp.getColour())
25Section 3.9
26DHTML Intro
- JavaScript can be used to manipulate the look and
content of an XHTML document after it has been
rendered. - This is refered to as Dynamic (X)HTML of DHTML
- In order to access the page elements and their
style Java Script uses the browsers Document
Object Model or DOM. - The DOM is not entirely standard across browsers
so we will only be looking at DOM functions that
are cross-browser.
27General Document Object Model
window
document
all
anchors
frames
applets
history
body
embeds
navigator
filters
location
forms
event
images
links
screen
plugins
Object
scripts
Collection
stylesheets
28Objects and Collections
- Objects
- window Object representation of browser window
- body Access to the body of the web page
- document XHTML document rendered in a window
- navigator Information regarding the web browser
- location URL of the current document
- event Information about an event that has
occurred in the page - Collections
- all Every element in the specified document (IE
- only)
- forms All forms in the document (in order of
appearance) - links, anchors All links/anchors in the document
29The window Object
- The window object represents the browser window.
It provides full access to the page properties - window status bar status
- current document location location
- document rendered in the window document
- the URL of the window location
- window also provides methods to
- open and close browser windows open()/close()
- interact with user prompt()/alert()/confirm()
- move/resize a window moveTo(x, y)/resizeTo(x, y)
30The window Object
- A number of predefined window objects exist
- self A reference to the current window
- opener A reference to the Window that opened the
- current Window
- Example - creating and second window and
redirecting it - ltscript language"Javascript"gt
- lt!--
- var newLocation self.prompt ("Enter
new location", "") - var myWindow self.open(newLocation)
- newLocation self.prompt ("Enter new
location again", "") - myWindow.location newLocation
- //--gt
- lt/scriptgt
31The location Object
- You can use the location object to control the
URL displayed in the browser window. - Properties
- location.href the entire current URL
- location.host the hostname and port
- location.hostname the hostname
- location.port the port number
- location.protocol the protocol
- location.pathname the pathname part of the URL
- Functions
- location.reload() refreshes the window
32The history Object
- The history Object gives you access to the
browsers history. - Properties
- history.current the current URL
- history.length the number of entries in the
history - Functions
- history.back() go back one page
- history.forward() go forward one page
- history.go() go forward/back the number of
pages specified. E.g. history.go(-2) takes you
back 2 while history.go(2) takes you forward 2.
33The navigator Object
- The navigator object contains browser
information. - This can be used to eneable scripts to
accommodate the DOM of multiple browsers - Properties
- navigator.appName the full name of the browser
- navigator.appCodeName browsers code type (e.g.
Mozilla) - navigator.appVersion the full version of the
browser - navigator.appMinorVersion the sub-version of
the browser - navigator.platform the platform the browser is
running on (e.g. Win32)
34The document Object
- The document object provides access to page
elements like images, tables, forms, scripts,
divs etc. - Properties
- Elements forms, links, anchors, scripts,
images - document.lastModified the date the file was
last edited - document.referrer the URL from which the user
came to this page - document.title the title of this page
35The document Object
- Functions
- document.getElementById(anID) returns a
reference to the object in the document with the
given ID. - document.close() close the document.
- document.write(), document.writeln() write to
the document. - document.clear() clear the document.
- document.open() re-open the document for
writing again. Can take an optional argument of a
mime-type.
36HTML Elements
- Every HTML tag is considered and element in the
DOM. - Properties
- className the CSS class of this element
- id the ID of this element
- innerHTML the HTML contained within this
element - outerHTML the HTML for this element including
the tag that created it. - parentNode this elements parent element
- style the stye for this element
37Accessing Individual Elements
- In order to access an element easily you have to
give it an ID. - You can then access it using document.getElementBy
Id(anID). - E.g.
- lth1 idhdg1gtSome Textlt/h1gt
- ltscript typetext/javascriptgtlt!--
- var hdg1 document.getElementById(hdg1)
- hdg1.innerHTML Edited using DHTML
- // --gt
- lt/scriptgt
38Accessing individual Elements
- When calling JavaScript functions from within an
event handeler you can get a reference to the
element that generated the event by using the
keyword this. - E.g.
- ltp onclick"this.style.colorwindow.prompt('Enter
a colour', '')"gtTesting the this key wordlt/pgt
39Editing Styles with DHTML
- You can edit the style of an element by either
editing its CSS class or by editing its style
properties individually. - To Edit the class use the Elements className
property and set it to the name of the class you
wish the element to become. - E.g.
- document.getElementById(test).className
myClass - You can access each individual style property
using the style property of the element. - E.g.
- document.getElementById(test).style.color
123123
40DOM and XHTML Properties
- Gernerally if an element supports an XHTML
attribute you can set that attribute using DHTML
by simply using the attribute name as a property
of the element. - E.g. for images the following will work
- theElement.src aURL
- theElement.alt Alt Text
- However, be carefull because this wil not always
work for all properties in all browsers. If at
all possible you should use the CSS properties
rather than the HTML attributes to edit the
element. In otherwords use - theElement.style.width 50
- Instead of
- theElement.width 50
41DOM and Forms
- When dealing with forms it is advisable to use
the old fassioned name attribute to access form
elements within the form rather than IDs because
some browsers have issues with form elements
having IDs. - E.g.
- ltform idmyForm action methodgetgt
- ltinput typetext namet1 /gt
- lt/formgt
- ltscript typetext/javascriptgtlt!
- var theForm document.getElementByID(myForm)
- theForm.t1.value edited with DHTML
- // --gt
- lt/scriptgt
42DOM and Forms
- Many form elements have extra properties and
functions associated with them. - form
- submit() submits the form
- reset() resets the form
- action the forms action
- method the forms method
- All form elements (except form)
- form a reference to the form the element
belongs to. - value the current value stored in the form
element.
43DOM and Forms
- input with type of radio or checkbox
- If there is more than one checkbox with the same
name (I.e. a group with more than one element)
the name will map to an array of form elements,
not a single element. - checked can be true or false and indicates
whether the checkbox/radio button is currently
checked - E.g.
- ltform action method idmfgt
- ltinput typeradio namea value3 /gt
- ltinput typeradio namea value4 /gt
- lt/formgt
- ltscript typetext/javascriptgtlt!
- var theForm document.getElementById(mf)
- theForm.a0.value2
- // --gt
- lt/scriptgt
44DOM and Forms
- select
- options an array contiang the option elements
for this select element - Each option element has the following properties
- value the value associated with this option
- text the text to display for this option
- selected true or false depending on whether the
option is currently selected.
45The End