Title: CM0133 Internet Computing JavaScript
1CM0133 Internet ComputingJavaScript
2Program Code in Web Pages
- There are many code types that can be included in
- web pages to increase interactivity
- Java Applets
- Visual Basic (Active Server Pages)
- PHP we will look at this
- Perl we will look at this
- JavaScript we will look at this
3PHP and Perl
- PHP and Perl run on a web server
- They generally handle complex or intensive tasks
- Search engines
- Logging internet usage
- Financial transactions
- Gathering Data/Stats
- Interfacing to databases
- Mathematical processing
- JavaScript is more suited to making pages Dynamic
and Interactive it allows HTML to be
manipulated - We will look at PHP and Perl later..
4JavaScript
- Typical Uses of Dynamic Web Pages (and
JavaScript) - Validating that Forms have been correctly filled
in - JavaScript will quickly do this before passing
data to Perl/PHP - Detecting which browser type accesses a page
- Opening new browser windows for links
- Messages, confirmations, alerts, status bars,
prompts - Rollover images, moving images, animations
- Multiple pages in a single download (dynamic
pages using layers..)
5JavaScript
- JavaScript code can be contained either
- within the web page, or
- contained in a file that is referenced by the
page - JavaScript is a simple language for fairly simple
tasks - Best suited for tasks which run for a short time
- Most commonly used to manipulate pieces of the
Document Object Model (DOM) - This allows JavaScript to interact and modify
HTML and is the key for providing page
interactivity. Cant do this with Perl/PHP
6JavaScript
- JavaScript syntax is very similar to that of Java
and C - JavaScript has
- variables, objects and functions (methods)
- blocks of code
- text output
- input forms and dialog boxes
- conditional structures (if...then...else)
- iterative structures (while... and for...)
- JavaScript has events associated with HTML
elements
7JavaScript
- Fragments of JavaScript code can be executed in
response to events - main modules and exit statements are not
necessary (unlike in standard Java..) - JavaScript is an interpreted language
- the script is compiled at run-time (unlike Java)
- JavaScript has no strict data typing (unlike
Java!!!!) - It is not necessary to declare the type of a
variable (except those of type object). - The interpreter will guess the data type (from
the surrounding context)
8Benefits of JavaScript
- It is widely supported in web browsers
- Gives easy access to document objects and can
manipulate most of them - Can produce animations without long download
times usually associated with multimedia - Surfers dont need special plug-ins to use your
scripts - JavaScript is relatively secure JavaScript
cannot read your hard-disk nor write to it, and
you cant get a virus from JavaScript.
9Problems with JavaScript
- Many scripts modify a pages DOM different
browsers use different DOMs.. - If scripts doesnt work then page is useless
- Many surfers disable JavaScript support in their
browser due to problem of broken scripts - Scripts can run slowly
- Complex scripts can take a long time to start up
10First Program..save as .html
- lthtmlgt
- ltheadgt
- ltscript language"javascript"gt
- lt!--
- document.writeln("Hello World! (from the
head)") - document.writeln("lth1gtHello World!lt/h1gt")
- --gt
- lt/scriptgt
- lt/headgt
- ltbodygt
- ltscript language"javascript"gt
- lt!--
- document.writeln("ltbgtHello World! (from the
body)lt/bgt") - --gt
- lt/scriptgt
- lt/bodygt
- lt/htmlgt
11Where does my code go?
- Code must be placed within ltscriptgt tags
- The ltscriptgt tag should include the
attribute-value pair language"javascript" - The contents of the script element should be
enclosed in a HTML comment so that it can be
ignored by older browsers (i.e. within lt!--
--gt) - You can use as many fragments as you want within
a web page - These can be placed in the head and body
- document.writeln writes to the screen
- HTML can be included in output strings e.g
lth1gt,ltbgt,etc
12Alerts
- lthtmlgt
- ltheadgt
- ltscript language"javascript"gt
- lt!--
- alert("Hi there!")
- --gt
- lt/scriptgt
- lt/headgt
- ltbodygtlt/bodygt
- lt/htmlgt
- Can prompt whenever you want
- String argument is output
13The Basics Variables
- JavaScript has variables like other languages
- Rules for variables
- Must begin with letter, digit or underscore
- No spaces in names
- Names are case sensitive
- Cant use reserved words (e.g. cant use var)
- In JavaScript you dont have to assign a variable
a data type!!! - E.g. dont have to do String myStringHi!
14The Basics Variables
- Variable type is not specified explicitly, but
determined by assignment. Use the var keyword for
declaration - Numbers
- var valueA
- var valueB 22, valueC 64.8
- valueA valueB valueC
- Strings
- var str1
- var str2 "hello there"
- str1 str2 " how are you"
- Boolean (true or false)
- condition_satisfied true
15The Basics Arrays
- Array declarations
- var values new Array(100)
- var nums 3, 6, 66, 3, 8, 10, 99
- Var days Monday,Tuesday,Wednesday
- Example
- Note that arrays begin at index 0(zero)
- Note that variables may be included in strings
using
var nums 1,2,3 document.writeln(first
value " nums0 ltbrgt)
document.writeln(second value " nums1
ltbrgt) document.writeln(third value "
nums2 ltbrgt)
16The Basics for loops
- for(initialise counter test condition
increment) - do something
var i var myArray 1,1,2,3,5,8,13 for(i0
iltmyArray.length() i) document.writeln("val
ue is " myArrayi) document.writeln("ltbrgt")
Note that you can use the length() function to
get the number of values in an array, e.g. Var
arrayLength myArray.length()
17while loops and do loops
while (condition is true) do something
count0 while(count lt 5) document.writeln("va
lue is " count) document.writeln("ltbrgt")
count count 1
- do something while (condition is true)
count0 do document.writeln("value is "
count) document.writeln("ltbrgt") count
count 1 while (count lt 5)
18The Basics if statements
- if (condition) do something
if(scoreA gt scoreB) document.writeln("The
winner is A")
if(scoreA gt scoreB) document.writeln("The
winner is A") else if (scoreA lt scoreB)
document.writeln("The winner is B") else
document.writeln("Everyone's a winner")
19Prompts
- ltheadgt
- ltscript language"javascript"gt
- lt!--
- var max_iters5var value0 var total0
- for(i0iltmax_itersi)
- value window.prompt("Enter a number","0")
- value parseInt(value)
- total total value
-
- average total/max_iters
- document.writeln("lth2gtAverage " average
"lt/h2gt") - //--gt
- lt/scriptgt
- lt/headgt
- ltbodygtRefresh or Reload to run the script again
- lt/bodygt
20Prompts
- window.prompt takes an input string from the user
and outputs a string - parseInt(value) converts an input string to an
Integer - Can also use parseFloat(value)
21Functions
- Functions are integral to JavaScript (and most
other languages..) - In JavaScript, functions are typically called in
response to user actions - This adds interactivity to pages
- Functions have to be declared within the head of
a document - Can then be used anywhere in a document (in the
body, in another function, etc)
22Functions
ltheadgt lttitlegtExample 1lt/titlegt ltscript
language"javascript"gt lt!-- function
showMessage() document.writeln(lth3gtHi
There..lt/h3gt") //Can also write more
functions here if required.. --gt
lt/scriptgt lt/headgt ltbodygt ltscript
language"javascript"gt showMessage()
lt/scriptgt lt/bodygt
We can also pass parameters to functions see
later examples. Note we can also write comments
using //
23Global and Local Variables
- Any variables declared within a function are
local to that function - Any variables declared outside a function are
global they may be used anywhere in the
program/page - You cannot use variables declared as local
outside of the function they are declared in - If you wanted you could use only global variables
but this is very bad programming practice.
24Example
- ltheadgtltscript language"javascript"gt
- lt!--
- var global_one 1 var global_two 100
- function doSomething()
- //local_one can only be used here!
- var local_one 10 var global_two 10
- document.writeln("local_one"local_one"ltbrgt")
- //can also use global_one - its a global
variable - document.writeln("global_one"global_one"ltbrgt"
) - document.writeln("global_two"global_two"ltbrgt"
) -
- --gt
- lt/scriptgt
- lt/headgtltbodygt
- ltscript language"javascript"gt
- doSomething()
- //I can use global_one here - not local_one
- document.writeln("global_one"global_one"ltbrgt"
) - document.writeln("global_two"global_two)
Whats the Value of global_two?
25Common Operators (JavaScript and Perl)
Adds numbers/Concatenates strings - Subtracts
numbers/Reverses sign Multiplies
numbers / Divides numbers Modulus division
(returns remainder from division) ! Logical
NOT gt Greater than lt Less than gt Greater than or
equal to lt Less than or equal to True if both
operands are equal ! True if both operands not
equal Logical AND Logical OR
26Some more basics Mathematics
- Can use Math class for powerful built in
functions - abs(value) - returns the absolute value
(modulus) - sin(value)/cos(value)/tan(value) - trigonometric
functions - max(value1,value2) - returns the larger value
- random() - returns a pseudorandom number between
0 and 1 - pow(value,power) result of value raised to
power - sqrt(value) returns square root of the number
- E.g. var result Math.sqrt(number)
27String manipulation
- charAt(index) e.g. myString.charAt(index)
- returns the character at position index in the
string. - concat(string) e.g. both str1.concat(str2)
- concatenates two strings
- length() e.g. size str1.length()
- returns the number of characters in the string
- split(separator) e.g. bits str.split(.)
- breaks the string apart whenever it encounters
the separator character (pieces returned in an
array) - toUpperCase()/toLowerCase()
- converts the string to upper/lower case
28Array functions
- join(sep)
- joins the array elements into a string (separated
by sep) - pop()
- removes the last element of the array
- push(element)
- adds an element to the end of the array
- reverse()
- reverses the order of the array elements
- shift()
- removes the first element of the array
- sort()
- sorts the array into lexicographic (dictionary)
order
29Document Object Model (DOM)
- Using JavaScript we can directly manipulate parts
of a web page making pages dynamic and
interactive - How is this done?
- JavaScript regards a webpage as a collection of
objects - We can manipulate object properties thus
manipulating the appearance of the web page - Objects are arranged into a hierarchy of objects
called the Document Object Model (DOM) - At the top of the hierarchy is the window object
this is your browser window - The document object is a child of the window
object this is the current webpage being
displayed
30A Simplified DOM
Elements
forms
anchors
links
Current Window
document
images
applets
embeds
- Note that certain objects contain arrays of
other objects - e.g. document object contains arrays for forms
and images
31Manipulating the document object
- Each object has certain properties and methods
- The document object has the following
properties/methods - writeln method to write out to the page
- write method to write out to the page
- bgColor change the body background colour
property - fgColor change the body foreground colour
property - The following program accesses and manipulates
properties of the document object - Note we have already seen the writeln method
32Manipulating the document object
- lthtmlgt
- ltheadgtlt/headgt
- ltbody bgColor"red"gt
- ltscript language"javascript"gt
- lt!--
- var backcolour document.bgColor
- document.write("The background colour is
"backcolour) - alert(Press to change from "backcolour" to
yellow") - document.bgColor "yellow"
- document.writeln("ltbrgtColour is now
"document.bgColor) - --gt
- lt/scriptgt
- lt/bodygt
- lt/htmlgt
33Manipulating the document object
34Events
- Before continuing with the DOM we should deviate
slightly - We will then see how to use images and forms
- We can call JavaScript functions in response to
events - These events can be triggered by the user
- Different event triggers are associated with
different HTML elements
35Selected event handlers
- onClick when the mouse button is clicked on an
element (e.g. used with the button and link
elements) - onMouseOver/onMouseOut when the mouse moves
into/ out of an element (e.g. used with the link,
image and layer elements). - onMouseDown/onMouseUp when the mouse button is
pressed/released. - onload/onunload when browser loads/finishes with
a document (used with the body element). - onFocus/onBlur when an element is
selected/deselected (i.e. another element is
selected) with the mouse (used with the input,
select, textarea and button elements). - onSubmit when the submit button pressed in a
form (used with the form element).
36onload/onunload Example
- ltheadgt
- ltscript language"javascript"gt
- lt!--
- function setbgColor()
- document.bgColor"red"
-
- function setAlert()
- alert("goodbye!")
-
- --gt
- lt/scriptgt
- lt/headgt
- ltbody onload"setbgColor()" onunload"setAlert()"
gt - lt/bodygt
37onclick example
ltheadgt ltscript language"javascript"gt lt!--
function change(col) if(col"red")
document.bgColor col if(col"blue")
document.bgColor col //--gt
lt/scriptgt lt/headgt ltbodygt ltformgt ltinput
type"button" value"Red" onClickchange("red")gt
ltinput type"button" value"Blue"
onClickchange("blue")gt lt/formgt lt/bodygt
38Arrays of objects
- Recap The DOM specifies various arrays of
objects e.g. forms, images, links - each array is indexed from 0
- These arrays contain objects as they appear on
the page - E.g. if you have two images on a page
- image0 contains the first image to appear
- image1 contains the second image to appear
39Accessing Object Properties
- Remember objects have properties that we can
read and change - Object properties typically correspond to
respective HTML attributes - E.g. images have properties for
- src the image source file name
- width the images width (pixels/percentage)
- height the images height (pixels/percentage)
40Rollovers
- We can modify an image objects properties to
create a rollover - A rollover is an image that changes its
appearance when the mouse moves over it, and
returns to its original state when the mouse
moves away - These are commonly used for dynamic hyperlinks
41Rollovers
- How is this achieved?
- We can access the filename for the first image on
a page like this - Var imageFileNamedocument.images0.src
- We can therefore change the image like this
- document.images0.src newFileName
42Rollovers
- We can use the onMouseOver and onMouseOut event
handlers to update the image file name
lthtmlgt ltheadgtlt/headgt ltbodygt ltimg src"cat_1.jpg"
onMouseOver"document.images0.src'cat_2.jpg'
" onMouseOut"document.images0.src'cat_1.jpg'
"gt lt/bodygt lt/htmlgt
- Note the use of single quotes.
43Rollovers
We can also put this in a hyperlink
lthtmlgt ltheadgtlt/headgt ltbodygt lta hrefcatwebpage.ht
mlgt ltimg src"cat_1.jpg" onMouseOver"document.i
mages0.src'cat_2.jpg' " onMouseOut"document.i
mages0.src'cat_1.jpg' "gt lt/agt lt/bodygt lt/htmlgt
The example above is the most common use of a
rollover image
44form objects
- Any data entered into a HTML form is contained in
a form object - An array forms contains all the form objects on
a page - Data from the first form on the page is contained
in the first array element, e.g. forms0 - Data from the second form on the page is
contained in the second element forms1 - etc..
45form and element objects
- A forms object contains another array, called
elements - An element refers to an input type, e.g. text,
password, checkbox, radio, - Input types are organised inside elements in
the order they appear in the specific form - For example, a page has two forms. The first form
has a text input and a submit button. The second
form has two standard buttons and a submit
button.
46form and element objects
text
elements0
forms0
submit
elements1
document
button
elements0
button
forms1
elements1
submit
elements2
47Where does this lead us?
- We now have access to data entered into a form.
- JavaScript is typically used to do initial checks
on form data before sending it to a server, e.g. - Ensures all fields are filled in
- Ensures that valid email addresses/URLs are
entered - The JavaScript program taking the form input can
also be standalone it doesnt have to send the
data onto a server (see Simple Calculator
Example). - NB Server side code may be written in PHP or
Perl (and others)
48Example Simple Calculator
- ltheadgtltscript language"javascript"gt
- lt!--
- function addNumbers()
- var num1 document.forms0.elements0.value
- var num2 document.forms0.elements1.value
- var result parseInt(num1) parseInt(num2)
- alert("Result " result)
-
- //--gt
- lt/scriptgtlt/headgtltbodygt
- ltform method"POST"gt
- Number 1 ltinput type"text" name"number_1"gtltbrgt
- Number 2 ltinput type"text" name"number_2"gtltbrgt
- ltinput type"button" value"Add
onClick"addNumbers()"gt - lt/formgtlt/bodygt
49Example Simple Calculator
- Pressing the button fires event onClick
- This calls addNumbers()
- Values entered into the text boxes are read
using - var num1 document.forms0.elements0.value
- var num2 document.forms0.elements1.value
-
- These values are initially strings
- They are converted to
- Integers using parseInt()
50Identifying by names
- This is a good point to introduce accessing
elements by name - We can give names to specific HTML elements
- We can then access the properties of that element
by referencing its name - This is an alternative to referencing an element
via its array location.
51Example Referencing by name
- ltheadgtltscript language"javascript"gt
- lt!--
- function addNumbers()
- var num1 document.myForm.number_1.value
- var num2 document.myForm.number_2.value
- var result parseInt(num1) parseInt(num2)
- alert("Result " result)
-
- //--gt
- lt/scriptgtlt/headgtltbodygt
- ltform name "myForm" method"POST"gt
- Number 1 ltinput type"text" name"number_1"gtltbrgt
- Number 2 ltinput type"text" name"number_2"gtltbrgt
- ltinput type"button" value"Add"
onClick"addNumbers()"gt - lt/formgtlt/bodygt
52Example Verifying form input
- We can use JavaScript to check forms before
sending data to a server - In this example
- The onSubmit event handler is fired when the
submit button is pressed - This calls function verifyForm()
- This returns false if there is missing data and
alerts the user - If it does not return false then the form data is
sent to processForm.php - NOTE we have not seen php programming yet
53Example
ltheadgt ltscript language"javascript"gt lt!--
function verifyForm() if(myForm.username.valu
e "" ) alert("Please enter a name")
return false if(myForm.address.value
"" ) alert("Please enter an address")
return false //--gt lt/scriptgt lt/headgt ltbo
dygt ltform name"myForm" method"POST"
action"processForm.php" onSubmit"return
verifyForm()"gt Name ltinput type"text"
name"username"gtltbrgt Addressltinput type"text"
name"address"gtltbrgt ltinput type"submit"
value"Send"gt lt/formgtlt/bodygt
54A more advanced form
- Lets look at a more advanced form
- Multiple input types
- Passes form object to function readForm as a
parameter - The script reads the form data and writes it to a
new window. We name this window win - Also note
- checked is used to determine whether or not a
check box is selected or not - The select element called rating contains an
array of options - selectedIndex is used to record the option
selected
55The Form
ltform name"feedbackForm" onSubmit"readForm(th
is)"gt lth2gtTell us what you thinklt/h2gt Name
ltinput type"text" name"username"gtltbrgt Address
ltinput type"text" name"address"
size"35"gtltbrgt lttablegtlttrgtlttdgt How did you find
this web site?ltbrgt Friendltinput type"checkbox"
name"how1" value"friend"gtltbrgt Googleltinput
type"checkbox" name"how2" value"google"gtltbrgt Ot
her ltinput type"checkbox" name"how3"
value"other"gtltbrgt lt/tdgtlttdgt How do you rate this
site? ltselect name"rating"gt ltoption
value"good"gtGood ltoption value"bad"gtBad ltoption
value"ugly"gtUgly lt/selectgt lt/tdgtlt/trgtlt/tablegt lth3
gtThank yoult/h3gt ltinput type"submit"
value"Send"gt ltinput type"reset"
value"Clear"gt lt/formgt
56The Script
function readForm(theForm) var i, optIdx,
rating win window.open("","messageWin")
win.document.writeln("lth2gtThe name is "
theForm.username.value "lt/h2gt")
win.document.writeln("lth2gtThe address is "
theForm.address.value "lt/h2gt")
win.document.writeln("lth2gtYou found us by
lt/h2gt") if(theForm.how1.checked)
win.document.writeln("ltbrgt"theForm.how1.value)
if(theForm.how2.checked)
win.document.writeln("ltbrgt"theForm.how2.value)
if(theForm.how3.checked)
win.document.writeln("ltbrgt"theForm.how3.value)
opIdx theForm.rating.selectedIndex
rating theForm.rating.optionsopIdx.value
win.document.writeln("lth2gtRating " rating
"lt/h2gt")
57Example Output
A message window created in response to user input
58Opening new windows
- We can also use the open method to open pages in
new windows often used for advertising/pop-ups
lthtmlgtltheadgt ltscript language"javascript"gt lt!-- o
pen("http//www.bbc.co.uk") --gt lt/scriptgt lt/headgt
ltbodygt lth1gtThis page loads another
pagelt/h1gt lt/bodygtlt/htmlgt
59Regular expressions
- Regular expressions are used for text processing
- Regular expressions are string patterns
- They are matched against strings to return the
result of the expression as e.g. an array,
boolean, or index - Regular expressions are an integral part of the
Perl programming language - Can also be used in JavaScript and PHP
60Regular expressions
- In JavaScript we may define static or dynamic
regular expressions - static pattern /fishfowl/
- dynamic pattern new RegExp("fishfowl")
- Static expressions can be created when the script
is first parsed good if performance is an issue - Dynamic expressions may be created at run time,
e.g. if search depends on user input
var pattern new RegExp("fishfowl") var
myString "Can you find the fish?" var results
pattern.exec(myString)
61Regular expressions
62Regular Expressions
- Examples
- fat matches to ft, fat, faat, faaat etc
- fat matches to fat, faat, faaat etc
- ba3t only matches to baaat
- Ffred matches to Fred or fred
- baiut will only match to bat, bit or but
- b.t will match to bat, bit, but, bct, bbt, etc..
- The dot (.) is used here as a wild card character
- ba1,4 matches to bat,baat,baaat and baaaat
- (abc) matches abc, abcabc, abcabcabc, etc..
- (ab)(cd) matches ac, ad, bc, bd
- \w matches first word at the beginning of a
string - \w \W \w matches first two words in a string
63Class string functions
- match(pattern)
- searches for a matching pattern. Returns an array
holding the results (or null if no match is
found) - replace(pattern, string)
- searches for pattern. If the search is
successful, pattern is replaced by string - search(pattern)
- searches for matching pattern. If the search is
successful, the index (offset) of the start of
the pattern is returned - split(pattern)
- splits the string into parts based on the pattern
(or regular expression) which is supplied as a
parameter
64Class RegExp functions
- exec(string)
- executes a search for a matching pattern. Returns
an array holding the result(s) of the operation - test(string)
- executes a search for a matching pattern. Returns
true if a match is found, false otherwise - Flags
- i ignore the case of the pattern and input
string - m search of data which spans several input
lines - g rather than stopping when a match is
successful, this forces global matching across
all of the input
65Example
- ltheadgtltscript language "javascript"gt
- lt!--
- var re1 new RegExp("fred","gi")
- // I could also write var re1 /Ffred/gi
- var msg1 "Fred, have you seen Fred recently?"
- var results re1.exec(msg1)
- if(results)
- alert("I found " results0)
- else
- alert("I didn't find it")
-
- var str1 "Darren"
- var msg2 msg1.replace(re1,str1)
- document.writeln(msg2)
- --gt
- lt/scriptgtlt/headgt
66Example
ltscript language"javascript"gt lt!-- function
checkURL() var url document.forms0.hom
eURL.value var url_pattern new
RegExp("http\/\/\w.\w")
if(!url.match(url_pattern)) alert("URL
not valid") return false
document.write("Thank you") return true
--gt lt/scriptgt ltform method"POST"
action"processing.php" onSubmit"return
checkURL()"gt ltpgtPlease enter the address of
your home pagelt/pgt ltpgtltinput type"text"
name"homeURL" size"40"gtlt/pgt ltpgtltinput
type"submit" value"Submit"gtlt/pgt lt/formgt
lt/bodygt
67Further modification of DOM objects
- We can also access, modify and set the style
attribute of page elements - We first give an element a unique id
- We modify style attributes with reference to this
id - Through the id we can also alter the document
content of an element e.g. we may change the text
between some ltpgt tags or ltbgt tags, etc - Note that we can also associate events with tags
such as ltpgt and ltbgt, etc
68Example 1
- lthtmlgt
- ltheadgt
- ltscript language"javascript"gt
- lt!--
- function move()
- para1.innerHTML"A bit bigger!"
- para1.style.fontSize 40
-
- --gt
- lt/scriptgt
- lt/headgt
- ltbodygt
- ltp id"para1" onClick"move()"gt
- Some words
- lt/pgt
- lt/bodygt
- lt/htmlgt
69Example 2
lthtmlgt ltheadgt lttitlegtLocationlt/titlegt
ltstylegt para1 position absolute
lt/stylegt ltscript language"javascript"gt lt!--
function move(elementid,x,y)
elementid.style.left x
elementid.style.top y elementid.innerHTML
"I moved" elementid.style.fontSize 40
--gt lt/scriptgt lt/headgt ltbodygt ltp
id"para1" onMouseOver"move(this,50,100)"gt
Some words lt/pgt lt/bodygt lt/htmlgt
70setInterval and clearInterval
- Used to call JavaScript code repeatedly at a
specified time interval
setInterval(code, interval)
- code is a string of JavaScript code (in quotes)
- interval is time in milliseconds
clearInterval(interval_Id)
- interval_Id is the value returned by setInterval
- To delay the execution of code, use setTimeout
and clearTimeout (same parameters)
71Animation
ltstylegt para1 position absolute color
red font-size 40pt lt/stylegt ltscript
language"javascript"gt var x 20, xshift 1
function move(elementId) x x
xshift elementId.style.left x if
(x gt 150) xshift -1
elementId.innerHTML "Goodbye!"
elementId.style.color "blue" if
(x lt 20 ) xshift 1
elementId.innerHTML "Hello!"
elementId.style.color "red"
lt/scriptgt
72Animation
ltbody onLoad"intervalId setInterval('move(para1
)',10)" onClick"clearInterval(intervalId)"gt
ltp id"para1" gt
Hello! lt/pgt lt/bodygt
73Browser Sniffing
- Your JavaScript code is not guaranteed to run on
all browsers - Each browser uses different Document Object Model
- Many developers ignore compatibility include
warnings e.g. page only works with IE 6 - However we can write scripts which are more
general than that.. - Solution
- We can detect the browser (browser sniffing) and
code for different versions
74Browser sniffing- further details
- The w3c have specified a standard document object
model for web browsers (see http//www.w3.org/DOM/
) - The Netscape DOM and the Internet Explorer DOM do
not comply with the standard DOM - However, Internet Explorer 5 and Netscape 6
have agreed on new set of standards which is
closer to the W3C DOM than previous versions
75Browser sniffing examples
- Information about the browser is contained in the
navigator object of the document object model - Using the appName property
var browser navigator.appName var Nav
(browser "Netscape") var IE (browser
"Internet Explorer)
- Using the appVersion property
var Nav navigator.appVersion.indexOf("Nav")gt0 v
ar IE navigator.appVersion.indexOf("MSIE")gt0
var version parseInt(navigator.appVersion) var
Nav4 ( Nav versiongt4) var IE4 (IE
versiongt4)
76Object detection
- Rather than explicitly detecting the client (then
using that particular client's objects and
methods), we simply check to see whether an
object exists before using it.
var isNetscape (document.layers) var isIE
(document.all) var isStandard
(document.getElementById)
- The existence of every object and method should
be tested before they are used. - It is risky to assume that if document.all
exists, then the client is running on Internet
Explorer (and hence that we can use all of IE's
DOM, not just document.all)