web programming introduction to javascript 1. the growth of the www has resulted in a demand for...
TRANSCRIPT
Web Programming Introduction to JavaScript
1
bull The growth of the WWW has resulted in a demand for dynamic and interactive websites
bull There are many different kinds of scripting languages ndash JavaScript hellip
bull This lecture aims at offering in‐depth knowledge of JavaScript discussing the complexity of scripting and studying various common examples
2
Introduction
Client-side language( run in the client browser)
Scripting language (interpreted in run-time)
Not compile like other language (C C++ VBNet etc)
JavaScript code can be inserted directly in the HTML or can place it in a separate file with the js extension and link the web page with the js file
Use in web browser for making a website more dynamic
Supported by Netscape 2+ Internet Explorer 3+ Opera 3+ and most of the other modern web browsers
Contains variable arrayobjectoperators and function
3
What is JavaScript
What is JavaScript
bull JavaScript was originally developed by Brendan Eich of
Netscape under the name Mocha which was later renamed
to LiveScript and finally to JavaScript
bull A lightweight programming language that runs in a Web
browser
bull JavaScript is a Client Side Scripting Language
bull Also known as ECMAScript
bull Interpreted not compiled
bull JavaScript Syntax are similar to C and Java Language
bull JavaScript code is usually embedded directly into HTML pages
bull JavaScript is reasonably platform-independent
bull JavaScript gives HTML designers a programming tool
bull JavaScript can put dynamic text into an HTML page
bull JavaScript can react to events
bull JavaScript can read and write HTML elements
bull JavaScript can be used to validate input data
bull JavaScript can be used to detect the visitors browser
bull JavaScript can be used to create cookies
What Can JavaScript Do
Used to perform operations that would otherwise encumber the server like form validation input
Can be easily used to interact with HTML elements such as validate text fields disable buttons validate forms or change the background color of page
Create dynamic page React to events such as the user enter name whenever
the page load for 1st time User can use entered value for welcome page
6
More usage of JavaScript
bull When you need to access other resourcesbull Files Programsbull Databases
bull When you are using sensitive or copyrighted data or algorithms
bull Your JavaScript code is open to the public
When not to use JavaScript
bullJava and JavaScript are two completely different languages in both concept and
design
bullJavaScript has some features that resemble features in Java
bull JavaScript has Objects and primitive data types
bull JavaScript has qualified names for example documentwrite(Hello World)
bull JavaScript has Events and event handlers
bull Exception handling in JavaScript is almost the same as in Java
bullJavaScript has some features unlike anything in Java
bull Variable names are untyped the type of a variable depends on the value it is
currently holding
bull Objects and arrays are defined in quite a different way
bull JavaScript is an interpreted language but java is both interpreted and compiled
JavaScript is not Java
Java VS JavaScript
Java JavaScript
Sun Microsystems Netscape
Much larger and advanced set of commands
Much smaller and simpler set of commands
Applets distinct from HTML (accessed from HTML pages)
Code integrated with and embedded in HTML
Variable data types must be declared (strong typing)
Variable data types not declared (loose typing)
Compiled on server before execution on client
Interpreted (not compiled) by client
9
JavaScript is written in the same way as HTML in a text editor (Notepad)
JavaScript implementation was quite similar to CSS you can link to outside files (with the file extension js) or write blocks of code into your HTML documents with the ltscriptgt tag
10
How to Put a JavaScript Into an HTML Page
bull JavaScript can be put in the ltheadgt or in the ltbodygt of an HTML documentbull JavaScript functions should be defined in the ltheadgt
bull This ensures that the function is loaded before it is needed
bull JavaScript in the ltbodygt will be executed as the page loads
bull JavaScript can be put in a separate js filebull ltscript src=myJavaScriptFilejsgtltscriptgtbull Put this HTML wherever you would put the actual
JavaScript codebull An external js file lets you use the same JavaScript on
multiple HTML pagesbull The external js file cannot itself contain a ltscriptgt tag
bull JavaScript can be put in HTML form object such as a buttonbull This JavaScript will be executed when the form object is
used
Where Do You Place Scripts
Scripts can either be in the ltheadgt section orltbodygt sectionbull Convention is to place it in the ltheadgt sectionlthtmlgtltheadgtltscript type=textjavascriptgtltscriptgtltheadgt
12
Placement Scripts
bull Scripts can be provided locally or remotely accessible JavaScript file using src attribute
lthtmlgtltheadgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=httpsomesitemyOwnJavaScriptjsgtltscriptgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=myOwnSubdirectorymyOwn2ndJavaScriptjsgtltscriptgt
Referencing External JavaScript File
Besides being an object oriented programming language JavaScript is also an event-driven language Lets take a look at what an event is
Whenever the user does something on a Web page whether its loading the page clicking on something or moving the mouse over something its called an event
For JavaScript to recognize an event we need an event handler Event handlers are easy to spot as they usually start with the word on Two commonly used event handlers are onclick and onmouseover
In the case of onmouseover it is attached to an object (lets say a link) on the page As soon as the user puts the mouse pointer over the object that this particular event handler is attached to then whatever you specify in the event handler will happen
The JavaScript event handler is placed inside an HTML tag like so lta href= onclick=windowclose()gtClose this windowltagt
14
What is an Event
onclick - Triggered when the object is clicked onmouseover - Triggered when the mouse moves over the object onmouseout - Triggered when the curser moves off of the object onblur - Triggered when the object is no longer selected (like a form object
or when a window is no longer in front onfocus - Triggered when an object is brought to focus such as bringing a
window in front of another onload - Triggered when the object is done loading onunload - Triggered when the user unloads the page (Loads another page
into the Window) onsubmit - Triggered when the user submits a form onselect - Triggered when the user selects the contents of an object onchange - Triggered when the user changes an object (such as making a
different selection in a form) onerror - Triggered when a JavaScript error is encountered onabort - Triggered when the user stops the page from loading
httpwwww3schoolscomjsjs_events_examplesasp15
Commonly used event handlers
16
lthtmlgt ltbodygt ltscript type=textjavascriptgt
documentwrite(HelloWorld)ltscriptgt ltbodygt lthtmlgt
The above code will produce this output on the HTML page
HelloWorld
17
To insert a JavaScript into an HTML page we use the ltscriptgt tag
The ltscript type=textjavascriptgt and ltscriptgt tells where the JavaScript starts and ends
The script tag encloses any script code you want to use The type attribute alert the browser to the type of script it is
about to deal with it helps in code interpretation
18
The comments around the script are there so that old browsers that donrsquot understand the script tag wonrsquot display the code as text on the page
If the browser can do JavaScript then it will ignore the comments
19
lthtmlgt ltbodygt ltscript type=textjavascriptgt ltscriptgt ltbodygt lthtmlgt
20
The word documentwrite is a standard JavaScript command for writing output to a page
If we had not entered the ltscriptgt tag the browser would have treated the documentwrite(Hello World) command as pure text and just write the entire line on the page
This will be the output
documentwrite(Hello World)
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
bull The growth of the WWW has resulted in a demand for dynamic and interactive websites
bull There are many different kinds of scripting languages ndash JavaScript hellip
bull This lecture aims at offering in‐depth knowledge of JavaScript discussing the complexity of scripting and studying various common examples
2
Introduction
Client-side language( run in the client browser)
Scripting language (interpreted in run-time)
Not compile like other language (C C++ VBNet etc)
JavaScript code can be inserted directly in the HTML or can place it in a separate file with the js extension and link the web page with the js file
Use in web browser for making a website more dynamic
Supported by Netscape 2+ Internet Explorer 3+ Opera 3+ and most of the other modern web browsers
Contains variable arrayobjectoperators and function
3
What is JavaScript
What is JavaScript
bull JavaScript was originally developed by Brendan Eich of
Netscape under the name Mocha which was later renamed
to LiveScript and finally to JavaScript
bull A lightweight programming language that runs in a Web
browser
bull JavaScript is a Client Side Scripting Language
bull Also known as ECMAScript
bull Interpreted not compiled
bull JavaScript Syntax are similar to C and Java Language
bull JavaScript code is usually embedded directly into HTML pages
bull JavaScript is reasonably platform-independent
bull JavaScript gives HTML designers a programming tool
bull JavaScript can put dynamic text into an HTML page
bull JavaScript can react to events
bull JavaScript can read and write HTML elements
bull JavaScript can be used to validate input data
bull JavaScript can be used to detect the visitors browser
bull JavaScript can be used to create cookies
What Can JavaScript Do
Used to perform operations that would otherwise encumber the server like form validation input
Can be easily used to interact with HTML elements such as validate text fields disable buttons validate forms or change the background color of page
Create dynamic page React to events such as the user enter name whenever
the page load for 1st time User can use entered value for welcome page
6
More usage of JavaScript
bull When you need to access other resourcesbull Files Programsbull Databases
bull When you are using sensitive or copyrighted data or algorithms
bull Your JavaScript code is open to the public
When not to use JavaScript
bullJava and JavaScript are two completely different languages in both concept and
design
bullJavaScript has some features that resemble features in Java
bull JavaScript has Objects and primitive data types
bull JavaScript has qualified names for example documentwrite(Hello World)
bull JavaScript has Events and event handlers
bull Exception handling in JavaScript is almost the same as in Java
bullJavaScript has some features unlike anything in Java
bull Variable names are untyped the type of a variable depends on the value it is
currently holding
bull Objects and arrays are defined in quite a different way
bull JavaScript is an interpreted language but java is both interpreted and compiled
JavaScript is not Java
Java VS JavaScript
Java JavaScript
Sun Microsystems Netscape
Much larger and advanced set of commands
Much smaller and simpler set of commands
Applets distinct from HTML (accessed from HTML pages)
Code integrated with and embedded in HTML
Variable data types must be declared (strong typing)
Variable data types not declared (loose typing)
Compiled on server before execution on client
Interpreted (not compiled) by client
9
JavaScript is written in the same way as HTML in a text editor (Notepad)
JavaScript implementation was quite similar to CSS you can link to outside files (with the file extension js) or write blocks of code into your HTML documents with the ltscriptgt tag
10
How to Put a JavaScript Into an HTML Page
bull JavaScript can be put in the ltheadgt or in the ltbodygt of an HTML documentbull JavaScript functions should be defined in the ltheadgt
bull This ensures that the function is loaded before it is needed
bull JavaScript in the ltbodygt will be executed as the page loads
bull JavaScript can be put in a separate js filebull ltscript src=myJavaScriptFilejsgtltscriptgtbull Put this HTML wherever you would put the actual
JavaScript codebull An external js file lets you use the same JavaScript on
multiple HTML pagesbull The external js file cannot itself contain a ltscriptgt tag
bull JavaScript can be put in HTML form object such as a buttonbull This JavaScript will be executed when the form object is
used
Where Do You Place Scripts
Scripts can either be in the ltheadgt section orltbodygt sectionbull Convention is to place it in the ltheadgt sectionlthtmlgtltheadgtltscript type=textjavascriptgtltscriptgtltheadgt
12
Placement Scripts
bull Scripts can be provided locally or remotely accessible JavaScript file using src attribute
lthtmlgtltheadgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=httpsomesitemyOwnJavaScriptjsgtltscriptgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=myOwnSubdirectorymyOwn2ndJavaScriptjsgtltscriptgt
Referencing External JavaScript File
Besides being an object oriented programming language JavaScript is also an event-driven language Lets take a look at what an event is
Whenever the user does something on a Web page whether its loading the page clicking on something or moving the mouse over something its called an event
For JavaScript to recognize an event we need an event handler Event handlers are easy to spot as they usually start with the word on Two commonly used event handlers are onclick and onmouseover
In the case of onmouseover it is attached to an object (lets say a link) on the page As soon as the user puts the mouse pointer over the object that this particular event handler is attached to then whatever you specify in the event handler will happen
The JavaScript event handler is placed inside an HTML tag like so lta href= onclick=windowclose()gtClose this windowltagt
14
What is an Event
onclick - Triggered when the object is clicked onmouseover - Triggered when the mouse moves over the object onmouseout - Triggered when the curser moves off of the object onblur - Triggered when the object is no longer selected (like a form object
or when a window is no longer in front onfocus - Triggered when an object is brought to focus such as bringing a
window in front of another onload - Triggered when the object is done loading onunload - Triggered when the user unloads the page (Loads another page
into the Window) onsubmit - Triggered when the user submits a form onselect - Triggered when the user selects the contents of an object onchange - Triggered when the user changes an object (such as making a
different selection in a form) onerror - Triggered when a JavaScript error is encountered onabort - Triggered when the user stops the page from loading
httpwwww3schoolscomjsjs_events_examplesasp15
Commonly used event handlers
16
lthtmlgt ltbodygt ltscript type=textjavascriptgt
documentwrite(HelloWorld)ltscriptgt ltbodygt lthtmlgt
The above code will produce this output on the HTML page
HelloWorld
17
To insert a JavaScript into an HTML page we use the ltscriptgt tag
The ltscript type=textjavascriptgt and ltscriptgt tells where the JavaScript starts and ends
The script tag encloses any script code you want to use The type attribute alert the browser to the type of script it is
about to deal with it helps in code interpretation
18
The comments around the script are there so that old browsers that donrsquot understand the script tag wonrsquot display the code as text on the page
If the browser can do JavaScript then it will ignore the comments
19
lthtmlgt ltbodygt ltscript type=textjavascriptgt ltscriptgt ltbodygt lthtmlgt
20
The word documentwrite is a standard JavaScript command for writing output to a page
If we had not entered the ltscriptgt tag the browser would have treated the documentwrite(Hello World) command as pure text and just write the entire line on the page
This will be the output
documentwrite(Hello World)
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Client-side language( run in the client browser)
Scripting language (interpreted in run-time)
Not compile like other language (C C++ VBNet etc)
JavaScript code can be inserted directly in the HTML or can place it in a separate file with the js extension and link the web page with the js file
Use in web browser for making a website more dynamic
Supported by Netscape 2+ Internet Explorer 3+ Opera 3+ and most of the other modern web browsers
Contains variable arrayobjectoperators and function
3
What is JavaScript
What is JavaScript
bull JavaScript was originally developed by Brendan Eich of
Netscape under the name Mocha which was later renamed
to LiveScript and finally to JavaScript
bull A lightweight programming language that runs in a Web
browser
bull JavaScript is a Client Side Scripting Language
bull Also known as ECMAScript
bull Interpreted not compiled
bull JavaScript Syntax are similar to C and Java Language
bull JavaScript code is usually embedded directly into HTML pages
bull JavaScript is reasonably platform-independent
bull JavaScript gives HTML designers a programming tool
bull JavaScript can put dynamic text into an HTML page
bull JavaScript can react to events
bull JavaScript can read and write HTML elements
bull JavaScript can be used to validate input data
bull JavaScript can be used to detect the visitors browser
bull JavaScript can be used to create cookies
What Can JavaScript Do
Used to perform operations that would otherwise encumber the server like form validation input
Can be easily used to interact with HTML elements such as validate text fields disable buttons validate forms or change the background color of page
Create dynamic page React to events such as the user enter name whenever
the page load for 1st time User can use entered value for welcome page
6
More usage of JavaScript
bull When you need to access other resourcesbull Files Programsbull Databases
bull When you are using sensitive or copyrighted data or algorithms
bull Your JavaScript code is open to the public
When not to use JavaScript
bullJava and JavaScript are two completely different languages in both concept and
design
bullJavaScript has some features that resemble features in Java
bull JavaScript has Objects and primitive data types
bull JavaScript has qualified names for example documentwrite(Hello World)
bull JavaScript has Events and event handlers
bull Exception handling in JavaScript is almost the same as in Java
bullJavaScript has some features unlike anything in Java
bull Variable names are untyped the type of a variable depends on the value it is
currently holding
bull Objects and arrays are defined in quite a different way
bull JavaScript is an interpreted language but java is both interpreted and compiled
JavaScript is not Java
Java VS JavaScript
Java JavaScript
Sun Microsystems Netscape
Much larger and advanced set of commands
Much smaller and simpler set of commands
Applets distinct from HTML (accessed from HTML pages)
Code integrated with and embedded in HTML
Variable data types must be declared (strong typing)
Variable data types not declared (loose typing)
Compiled on server before execution on client
Interpreted (not compiled) by client
9
JavaScript is written in the same way as HTML in a text editor (Notepad)
JavaScript implementation was quite similar to CSS you can link to outside files (with the file extension js) or write blocks of code into your HTML documents with the ltscriptgt tag
10
How to Put a JavaScript Into an HTML Page
bull JavaScript can be put in the ltheadgt or in the ltbodygt of an HTML documentbull JavaScript functions should be defined in the ltheadgt
bull This ensures that the function is loaded before it is needed
bull JavaScript in the ltbodygt will be executed as the page loads
bull JavaScript can be put in a separate js filebull ltscript src=myJavaScriptFilejsgtltscriptgtbull Put this HTML wherever you would put the actual
JavaScript codebull An external js file lets you use the same JavaScript on
multiple HTML pagesbull The external js file cannot itself contain a ltscriptgt tag
bull JavaScript can be put in HTML form object such as a buttonbull This JavaScript will be executed when the form object is
used
Where Do You Place Scripts
Scripts can either be in the ltheadgt section orltbodygt sectionbull Convention is to place it in the ltheadgt sectionlthtmlgtltheadgtltscript type=textjavascriptgtltscriptgtltheadgt
12
Placement Scripts
bull Scripts can be provided locally or remotely accessible JavaScript file using src attribute
lthtmlgtltheadgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=httpsomesitemyOwnJavaScriptjsgtltscriptgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=myOwnSubdirectorymyOwn2ndJavaScriptjsgtltscriptgt
Referencing External JavaScript File
Besides being an object oriented programming language JavaScript is also an event-driven language Lets take a look at what an event is
Whenever the user does something on a Web page whether its loading the page clicking on something or moving the mouse over something its called an event
For JavaScript to recognize an event we need an event handler Event handlers are easy to spot as they usually start with the word on Two commonly used event handlers are onclick and onmouseover
In the case of onmouseover it is attached to an object (lets say a link) on the page As soon as the user puts the mouse pointer over the object that this particular event handler is attached to then whatever you specify in the event handler will happen
The JavaScript event handler is placed inside an HTML tag like so lta href= onclick=windowclose()gtClose this windowltagt
14
What is an Event
onclick - Triggered when the object is clicked onmouseover - Triggered when the mouse moves over the object onmouseout - Triggered when the curser moves off of the object onblur - Triggered when the object is no longer selected (like a form object
or when a window is no longer in front onfocus - Triggered when an object is brought to focus such as bringing a
window in front of another onload - Triggered when the object is done loading onunload - Triggered when the user unloads the page (Loads another page
into the Window) onsubmit - Triggered when the user submits a form onselect - Triggered when the user selects the contents of an object onchange - Triggered when the user changes an object (such as making a
different selection in a form) onerror - Triggered when a JavaScript error is encountered onabort - Triggered when the user stops the page from loading
httpwwww3schoolscomjsjs_events_examplesasp15
Commonly used event handlers
16
lthtmlgt ltbodygt ltscript type=textjavascriptgt
documentwrite(HelloWorld)ltscriptgt ltbodygt lthtmlgt
The above code will produce this output on the HTML page
HelloWorld
17
To insert a JavaScript into an HTML page we use the ltscriptgt tag
The ltscript type=textjavascriptgt and ltscriptgt tells where the JavaScript starts and ends
The script tag encloses any script code you want to use The type attribute alert the browser to the type of script it is
about to deal with it helps in code interpretation
18
The comments around the script are there so that old browsers that donrsquot understand the script tag wonrsquot display the code as text on the page
If the browser can do JavaScript then it will ignore the comments
19
lthtmlgt ltbodygt ltscript type=textjavascriptgt ltscriptgt ltbodygt lthtmlgt
20
The word documentwrite is a standard JavaScript command for writing output to a page
If we had not entered the ltscriptgt tag the browser would have treated the documentwrite(Hello World) command as pure text and just write the entire line on the page
This will be the output
documentwrite(Hello World)
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
What is JavaScript
bull JavaScript was originally developed by Brendan Eich of
Netscape under the name Mocha which was later renamed
to LiveScript and finally to JavaScript
bull A lightweight programming language that runs in a Web
browser
bull JavaScript is a Client Side Scripting Language
bull Also known as ECMAScript
bull Interpreted not compiled
bull JavaScript Syntax are similar to C and Java Language
bull JavaScript code is usually embedded directly into HTML pages
bull JavaScript is reasonably platform-independent
bull JavaScript gives HTML designers a programming tool
bull JavaScript can put dynamic text into an HTML page
bull JavaScript can react to events
bull JavaScript can read and write HTML elements
bull JavaScript can be used to validate input data
bull JavaScript can be used to detect the visitors browser
bull JavaScript can be used to create cookies
What Can JavaScript Do
Used to perform operations that would otherwise encumber the server like form validation input
Can be easily used to interact with HTML elements such as validate text fields disable buttons validate forms or change the background color of page
Create dynamic page React to events such as the user enter name whenever
the page load for 1st time User can use entered value for welcome page
6
More usage of JavaScript
bull When you need to access other resourcesbull Files Programsbull Databases
bull When you are using sensitive or copyrighted data or algorithms
bull Your JavaScript code is open to the public
When not to use JavaScript
bullJava and JavaScript are two completely different languages in both concept and
design
bullJavaScript has some features that resemble features in Java
bull JavaScript has Objects and primitive data types
bull JavaScript has qualified names for example documentwrite(Hello World)
bull JavaScript has Events and event handlers
bull Exception handling in JavaScript is almost the same as in Java
bullJavaScript has some features unlike anything in Java
bull Variable names are untyped the type of a variable depends on the value it is
currently holding
bull Objects and arrays are defined in quite a different way
bull JavaScript is an interpreted language but java is both interpreted and compiled
JavaScript is not Java
Java VS JavaScript
Java JavaScript
Sun Microsystems Netscape
Much larger and advanced set of commands
Much smaller and simpler set of commands
Applets distinct from HTML (accessed from HTML pages)
Code integrated with and embedded in HTML
Variable data types must be declared (strong typing)
Variable data types not declared (loose typing)
Compiled on server before execution on client
Interpreted (not compiled) by client
9
JavaScript is written in the same way as HTML in a text editor (Notepad)
JavaScript implementation was quite similar to CSS you can link to outside files (with the file extension js) or write blocks of code into your HTML documents with the ltscriptgt tag
10
How to Put a JavaScript Into an HTML Page
bull JavaScript can be put in the ltheadgt or in the ltbodygt of an HTML documentbull JavaScript functions should be defined in the ltheadgt
bull This ensures that the function is loaded before it is needed
bull JavaScript in the ltbodygt will be executed as the page loads
bull JavaScript can be put in a separate js filebull ltscript src=myJavaScriptFilejsgtltscriptgtbull Put this HTML wherever you would put the actual
JavaScript codebull An external js file lets you use the same JavaScript on
multiple HTML pagesbull The external js file cannot itself contain a ltscriptgt tag
bull JavaScript can be put in HTML form object such as a buttonbull This JavaScript will be executed when the form object is
used
Where Do You Place Scripts
Scripts can either be in the ltheadgt section orltbodygt sectionbull Convention is to place it in the ltheadgt sectionlthtmlgtltheadgtltscript type=textjavascriptgtltscriptgtltheadgt
12
Placement Scripts
bull Scripts can be provided locally or remotely accessible JavaScript file using src attribute
lthtmlgtltheadgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=httpsomesitemyOwnJavaScriptjsgtltscriptgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=myOwnSubdirectorymyOwn2ndJavaScriptjsgtltscriptgt
Referencing External JavaScript File
Besides being an object oriented programming language JavaScript is also an event-driven language Lets take a look at what an event is
Whenever the user does something on a Web page whether its loading the page clicking on something or moving the mouse over something its called an event
For JavaScript to recognize an event we need an event handler Event handlers are easy to spot as they usually start with the word on Two commonly used event handlers are onclick and onmouseover
In the case of onmouseover it is attached to an object (lets say a link) on the page As soon as the user puts the mouse pointer over the object that this particular event handler is attached to then whatever you specify in the event handler will happen
The JavaScript event handler is placed inside an HTML tag like so lta href= onclick=windowclose()gtClose this windowltagt
14
What is an Event
onclick - Triggered when the object is clicked onmouseover - Triggered when the mouse moves over the object onmouseout - Triggered when the curser moves off of the object onblur - Triggered when the object is no longer selected (like a form object
or when a window is no longer in front onfocus - Triggered when an object is brought to focus such as bringing a
window in front of another onload - Triggered when the object is done loading onunload - Triggered when the user unloads the page (Loads another page
into the Window) onsubmit - Triggered when the user submits a form onselect - Triggered when the user selects the contents of an object onchange - Triggered when the user changes an object (such as making a
different selection in a form) onerror - Triggered when a JavaScript error is encountered onabort - Triggered when the user stops the page from loading
httpwwww3schoolscomjsjs_events_examplesasp15
Commonly used event handlers
16
lthtmlgt ltbodygt ltscript type=textjavascriptgt
documentwrite(HelloWorld)ltscriptgt ltbodygt lthtmlgt
The above code will produce this output on the HTML page
HelloWorld
17
To insert a JavaScript into an HTML page we use the ltscriptgt tag
The ltscript type=textjavascriptgt and ltscriptgt tells where the JavaScript starts and ends
The script tag encloses any script code you want to use The type attribute alert the browser to the type of script it is
about to deal with it helps in code interpretation
18
The comments around the script are there so that old browsers that donrsquot understand the script tag wonrsquot display the code as text on the page
If the browser can do JavaScript then it will ignore the comments
19
lthtmlgt ltbodygt ltscript type=textjavascriptgt ltscriptgt ltbodygt lthtmlgt
20
The word documentwrite is a standard JavaScript command for writing output to a page
If we had not entered the ltscriptgt tag the browser would have treated the documentwrite(Hello World) command as pure text and just write the entire line on the page
This will be the output
documentwrite(Hello World)
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
bull JavaScript gives HTML designers a programming tool
bull JavaScript can put dynamic text into an HTML page
bull JavaScript can react to events
bull JavaScript can read and write HTML elements
bull JavaScript can be used to validate input data
bull JavaScript can be used to detect the visitors browser
bull JavaScript can be used to create cookies
What Can JavaScript Do
Used to perform operations that would otherwise encumber the server like form validation input
Can be easily used to interact with HTML elements such as validate text fields disable buttons validate forms or change the background color of page
Create dynamic page React to events such as the user enter name whenever
the page load for 1st time User can use entered value for welcome page
6
More usage of JavaScript
bull When you need to access other resourcesbull Files Programsbull Databases
bull When you are using sensitive or copyrighted data or algorithms
bull Your JavaScript code is open to the public
When not to use JavaScript
bullJava and JavaScript are two completely different languages in both concept and
design
bullJavaScript has some features that resemble features in Java
bull JavaScript has Objects and primitive data types
bull JavaScript has qualified names for example documentwrite(Hello World)
bull JavaScript has Events and event handlers
bull Exception handling in JavaScript is almost the same as in Java
bullJavaScript has some features unlike anything in Java
bull Variable names are untyped the type of a variable depends on the value it is
currently holding
bull Objects and arrays are defined in quite a different way
bull JavaScript is an interpreted language but java is both interpreted and compiled
JavaScript is not Java
Java VS JavaScript
Java JavaScript
Sun Microsystems Netscape
Much larger and advanced set of commands
Much smaller and simpler set of commands
Applets distinct from HTML (accessed from HTML pages)
Code integrated with and embedded in HTML
Variable data types must be declared (strong typing)
Variable data types not declared (loose typing)
Compiled on server before execution on client
Interpreted (not compiled) by client
9
JavaScript is written in the same way as HTML in a text editor (Notepad)
JavaScript implementation was quite similar to CSS you can link to outside files (with the file extension js) or write blocks of code into your HTML documents with the ltscriptgt tag
10
How to Put a JavaScript Into an HTML Page
bull JavaScript can be put in the ltheadgt or in the ltbodygt of an HTML documentbull JavaScript functions should be defined in the ltheadgt
bull This ensures that the function is loaded before it is needed
bull JavaScript in the ltbodygt will be executed as the page loads
bull JavaScript can be put in a separate js filebull ltscript src=myJavaScriptFilejsgtltscriptgtbull Put this HTML wherever you would put the actual
JavaScript codebull An external js file lets you use the same JavaScript on
multiple HTML pagesbull The external js file cannot itself contain a ltscriptgt tag
bull JavaScript can be put in HTML form object such as a buttonbull This JavaScript will be executed when the form object is
used
Where Do You Place Scripts
Scripts can either be in the ltheadgt section orltbodygt sectionbull Convention is to place it in the ltheadgt sectionlthtmlgtltheadgtltscript type=textjavascriptgtltscriptgtltheadgt
12
Placement Scripts
bull Scripts can be provided locally or remotely accessible JavaScript file using src attribute
lthtmlgtltheadgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=httpsomesitemyOwnJavaScriptjsgtltscriptgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=myOwnSubdirectorymyOwn2ndJavaScriptjsgtltscriptgt
Referencing External JavaScript File
Besides being an object oriented programming language JavaScript is also an event-driven language Lets take a look at what an event is
Whenever the user does something on a Web page whether its loading the page clicking on something or moving the mouse over something its called an event
For JavaScript to recognize an event we need an event handler Event handlers are easy to spot as they usually start with the word on Two commonly used event handlers are onclick and onmouseover
In the case of onmouseover it is attached to an object (lets say a link) on the page As soon as the user puts the mouse pointer over the object that this particular event handler is attached to then whatever you specify in the event handler will happen
The JavaScript event handler is placed inside an HTML tag like so lta href= onclick=windowclose()gtClose this windowltagt
14
What is an Event
onclick - Triggered when the object is clicked onmouseover - Triggered when the mouse moves over the object onmouseout - Triggered when the curser moves off of the object onblur - Triggered when the object is no longer selected (like a form object
or when a window is no longer in front onfocus - Triggered when an object is brought to focus such as bringing a
window in front of another onload - Triggered when the object is done loading onunload - Triggered when the user unloads the page (Loads another page
into the Window) onsubmit - Triggered when the user submits a form onselect - Triggered when the user selects the contents of an object onchange - Triggered when the user changes an object (such as making a
different selection in a form) onerror - Triggered when a JavaScript error is encountered onabort - Triggered when the user stops the page from loading
httpwwww3schoolscomjsjs_events_examplesasp15
Commonly used event handlers
16
lthtmlgt ltbodygt ltscript type=textjavascriptgt
documentwrite(HelloWorld)ltscriptgt ltbodygt lthtmlgt
The above code will produce this output on the HTML page
HelloWorld
17
To insert a JavaScript into an HTML page we use the ltscriptgt tag
The ltscript type=textjavascriptgt and ltscriptgt tells where the JavaScript starts and ends
The script tag encloses any script code you want to use The type attribute alert the browser to the type of script it is
about to deal with it helps in code interpretation
18
The comments around the script are there so that old browsers that donrsquot understand the script tag wonrsquot display the code as text on the page
If the browser can do JavaScript then it will ignore the comments
19
lthtmlgt ltbodygt ltscript type=textjavascriptgt ltscriptgt ltbodygt lthtmlgt
20
The word documentwrite is a standard JavaScript command for writing output to a page
If we had not entered the ltscriptgt tag the browser would have treated the documentwrite(Hello World) command as pure text and just write the entire line on the page
This will be the output
documentwrite(Hello World)
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Used to perform operations that would otherwise encumber the server like form validation input
Can be easily used to interact with HTML elements such as validate text fields disable buttons validate forms or change the background color of page
Create dynamic page React to events such as the user enter name whenever
the page load for 1st time User can use entered value for welcome page
6
More usage of JavaScript
bull When you need to access other resourcesbull Files Programsbull Databases
bull When you are using sensitive or copyrighted data or algorithms
bull Your JavaScript code is open to the public
When not to use JavaScript
bullJava and JavaScript are two completely different languages in both concept and
design
bullJavaScript has some features that resemble features in Java
bull JavaScript has Objects and primitive data types
bull JavaScript has qualified names for example documentwrite(Hello World)
bull JavaScript has Events and event handlers
bull Exception handling in JavaScript is almost the same as in Java
bullJavaScript has some features unlike anything in Java
bull Variable names are untyped the type of a variable depends on the value it is
currently holding
bull Objects and arrays are defined in quite a different way
bull JavaScript is an interpreted language but java is both interpreted and compiled
JavaScript is not Java
Java VS JavaScript
Java JavaScript
Sun Microsystems Netscape
Much larger and advanced set of commands
Much smaller and simpler set of commands
Applets distinct from HTML (accessed from HTML pages)
Code integrated with and embedded in HTML
Variable data types must be declared (strong typing)
Variable data types not declared (loose typing)
Compiled on server before execution on client
Interpreted (not compiled) by client
9
JavaScript is written in the same way as HTML in a text editor (Notepad)
JavaScript implementation was quite similar to CSS you can link to outside files (with the file extension js) or write blocks of code into your HTML documents with the ltscriptgt tag
10
How to Put a JavaScript Into an HTML Page
bull JavaScript can be put in the ltheadgt or in the ltbodygt of an HTML documentbull JavaScript functions should be defined in the ltheadgt
bull This ensures that the function is loaded before it is needed
bull JavaScript in the ltbodygt will be executed as the page loads
bull JavaScript can be put in a separate js filebull ltscript src=myJavaScriptFilejsgtltscriptgtbull Put this HTML wherever you would put the actual
JavaScript codebull An external js file lets you use the same JavaScript on
multiple HTML pagesbull The external js file cannot itself contain a ltscriptgt tag
bull JavaScript can be put in HTML form object such as a buttonbull This JavaScript will be executed when the form object is
used
Where Do You Place Scripts
Scripts can either be in the ltheadgt section orltbodygt sectionbull Convention is to place it in the ltheadgt sectionlthtmlgtltheadgtltscript type=textjavascriptgtltscriptgtltheadgt
12
Placement Scripts
bull Scripts can be provided locally or remotely accessible JavaScript file using src attribute
lthtmlgtltheadgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=httpsomesitemyOwnJavaScriptjsgtltscriptgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=myOwnSubdirectorymyOwn2ndJavaScriptjsgtltscriptgt
Referencing External JavaScript File
Besides being an object oriented programming language JavaScript is also an event-driven language Lets take a look at what an event is
Whenever the user does something on a Web page whether its loading the page clicking on something or moving the mouse over something its called an event
For JavaScript to recognize an event we need an event handler Event handlers are easy to spot as they usually start with the word on Two commonly used event handlers are onclick and onmouseover
In the case of onmouseover it is attached to an object (lets say a link) on the page As soon as the user puts the mouse pointer over the object that this particular event handler is attached to then whatever you specify in the event handler will happen
The JavaScript event handler is placed inside an HTML tag like so lta href= onclick=windowclose()gtClose this windowltagt
14
What is an Event
onclick - Triggered when the object is clicked onmouseover - Triggered when the mouse moves over the object onmouseout - Triggered when the curser moves off of the object onblur - Triggered when the object is no longer selected (like a form object
or when a window is no longer in front onfocus - Triggered when an object is brought to focus such as bringing a
window in front of another onload - Triggered when the object is done loading onunload - Triggered when the user unloads the page (Loads another page
into the Window) onsubmit - Triggered when the user submits a form onselect - Triggered when the user selects the contents of an object onchange - Triggered when the user changes an object (such as making a
different selection in a form) onerror - Triggered when a JavaScript error is encountered onabort - Triggered when the user stops the page from loading
httpwwww3schoolscomjsjs_events_examplesasp15
Commonly used event handlers
16
lthtmlgt ltbodygt ltscript type=textjavascriptgt
documentwrite(HelloWorld)ltscriptgt ltbodygt lthtmlgt
The above code will produce this output on the HTML page
HelloWorld
17
To insert a JavaScript into an HTML page we use the ltscriptgt tag
The ltscript type=textjavascriptgt and ltscriptgt tells where the JavaScript starts and ends
The script tag encloses any script code you want to use The type attribute alert the browser to the type of script it is
about to deal with it helps in code interpretation
18
The comments around the script are there so that old browsers that donrsquot understand the script tag wonrsquot display the code as text on the page
If the browser can do JavaScript then it will ignore the comments
19
lthtmlgt ltbodygt ltscript type=textjavascriptgt ltscriptgt ltbodygt lthtmlgt
20
The word documentwrite is a standard JavaScript command for writing output to a page
If we had not entered the ltscriptgt tag the browser would have treated the documentwrite(Hello World) command as pure text and just write the entire line on the page
This will be the output
documentwrite(Hello World)
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
bull When you need to access other resourcesbull Files Programsbull Databases
bull When you are using sensitive or copyrighted data or algorithms
bull Your JavaScript code is open to the public
When not to use JavaScript
bullJava and JavaScript are two completely different languages in both concept and
design
bullJavaScript has some features that resemble features in Java
bull JavaScript has Objects and primitive data types
bull JavaScript has qualified names for example documentwrite(Hello World)
bull JavaScript has Events and event handlers
bull Exception handling in JavaScript is almost the same as in Java
bullJavaScript has some features unlike anything in Java
bull Variable names are untyped the type of a variable depends on the value it is
currently holding
bull Objects and arrays are defined in quite a different way
bull JavaScript is an interpreted language but java is both interpreted and compiled
JavaScript is not Java
Java VS JavaScript
Java JavaScript
Sun Microsystems Netscape
Much larger and advanced set of commands
Much smaller and simpler set of commands
Applets distinct from HTML (accessed from HTML pages)
Code integrated with and embedded in HTML
Variable data types must be declared (strong typing)
Variable data types not declared (loose typing)
Compiled on server before execution on client
Interpreted (not compiled) by client
9
JavaScript is written in the same way as HTML in a text editor (Notepad)
JavaScript implementation was quite similar to CSS you can link to outside files (with the file extension js) or write blocks of code into your HTML documents with the ltscriptgt tag
10
How to Put a JavaScript Into an HTML Page
bull JavaScript can be put in the ltheadgt or in the ltbodygt of an HTML documentbull JavaScript functions should be defined in the ltheadgt
bull This ensures that the function is loaded before it is needed
bull JavaScript in the ltbodygt will be executed as the page loads
bull JavaScript can be put in a separate js filebull ltscript src=myJavaScriptFilejsgtltscriptgtbull Put this HTML wherever you would put the actual
JavaScript codebull An external js file lets you use the same JavaScript on
multiple HTML pagesbull The external js file cannot itself contain a ltscriptgt tag
bull JavaScript can be put in HTML form object such as a buttonbull This JavaScript will be executed when the form object is
used
Where Do You Place Scripts
Scripts can either be in the ltheadgt section orltbodygt sectionbull Convention is to place it in the ltheadgt sectionlthtmlgtltheadgtltscript type=textjavascriptgtltscriptgtltheadgt
12
Placement Scripts
bull Scripts can be provided locally or remotely accessible JavaScript file using src attribute
lthtmlgtltheadgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=httpsomesitemyOwnJavaScriptjsgtltscriptgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=myOwnSubdirectorymyOwn2ndJavaScriptjsgtltscriptgt
Referencing External JavaScript File
Besides being an object oriented programming language JavaScript is also an event-driven language Lets take a look at what an event is
Whenever the user does something on a Web page whether its loading the page clicking on something or moving the mouse over something its called an event
For JavaScript to recognize an event we need an event handler Event handlers are easy to spot as they usually start with the word on Two commonly used event handlers are onclick and onmouseover
In the case of onmouseover it is attached to an object (lets say a link) on the page As soon as the user puts the mouse pointer over the object that this particular event handler is attached to then whatever you specify in the event handler will happen
The JavaScript event handler is placed inside an HTML tag like so lta href= onclick=windowclose()gtClose this windowltagt
14
What is an Event
onclick - Triggered when the object is clicked onmouseover - Triggered when the mouse moves over the object onmouseout - Triggered when the curser moves off of the object onblur - Triggered when the object is no longer selected (like a form object
or when a window is no longer in front onfocus - Triggered when an object is brought to focus such as bringing a
window in front of another onload - Triggered when the object is done loading onunload - Triggered when the user unloads the page (Loads another page
into the Window) onsubmit - Triggered when the user submits a form onselect - Triggered when the user selects the contents of an object onchange - Triggered when the user changes an object (such as making a
different selection in a form) onerror - Triggered when a JavaScript error is encountered onabort - Triggered when the user stops the page from loading
httpwwww3schoolscomjsjs_events_examplesasp15
Commonly used event handlers
16
lthtmlgt ltbodygt ltscript type=textjavascriptgt
documentwrite(HelloWorld)ltscriptgt ltbodygt lthtmlgt
The above code will produce this output on the HTML page
HelloWorld
17
To insert a JavaScript into an HTML page we use the ltscriptgt tag
The ltscript type=textjavascriptgt and ltscriptgt tells where the JavaScript starts and ends
The script tag encloses any script code you want to use The type attribute alert the browser to the type of script it is
about to deal with it helps in code interpretation
18
The comments around the script are there so that old browsers that donrsquot understand the script tag wonrsquot display the code as text on the page
If the browser can do JavaScript then it will ignore the comments
19
lthtmlgt ltbodygt ltscript type=textjavascriptgt ltscriptgt ltbodygt lthtmlgt
20
The word documentwrite is a standard JavaScript command for writing output to a page
If we had not entered the ltscriptgt tag the browser would have treated the documentwrite(Hello World) command as pure text and just write the entire line on the page
This will be the output
documentwrite(Hello World)
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
bullJava and JavaScript are two completely different languages in both concept and
design
bullJavaScript has some features that resemble features in Java
bull JavaScript has Objects and primitive data types
bull JavaScript has qualified names for example documentwrite(Hello World)
bull JavaScript has Events and event handlers
bull Exception handling in JavaScript is almost the same as in Java
bullJavaScript has some features unlike anything in Java
bull Variable names are untyped the type of a variable depends on the value it is
currently holding
bull Objects and arrays are defined in quite a different way
bull JavaScript is an interpreted language but java is both interpreted and compiled
JavaScript is not Java
Java VS JavaScript
Java JavaScript
Sun Microsystems Netscape
Much larger and advanced set of commands
Much smaller and simpler set of commands
Applets distinct from HTML (accessed from HTML pages)
Code integrated with and embedded in HTML
Variable data types must be declared (strong typing)
Variable data types not declared (loose typing)
Compiled on server before execution on client
Interpreted (not compiled) by client
9
JavaScript is written in the same way as HTML in a text editor (Notepad)
JavaScript implementation was quite similar to CSS you can link to outside files (with the file extension js) or write blocks of code into your HTML documents with the ltscriptgt tag
10
How to Put a JavaScript Into an HTML Page
bull JavaScript can be put in the ltheadgt or in the ltbodygt of an HTML documentbull JavaScript functions should be defined in the ltheadgt
bull This ensures that the function is loaded before it is needed
bull JavaScript in the ltbodygt will be executed as the page loads
bull JavaScript can be put in a separate js filebull ltscript src=myJavaScriptFilejsgtltscriptgtbull Put this HTML wherever you would put the actual
JavaScript codebull An external js file lets you use the same JavaScript on
multiple HTML pagesbull The external js file cannot itself contain a ltscriptgt tag
bull JavaScript can be put in HTML form object such as a buttonbull This JavaScript will be executed when the form object is
used
Where Do You Place Scripts
Scripts can either be in the ltheadgt section orltbodygt sectionbull Convention is to place it in the ltheadgt sectionlthtmlgtltheadgtltscript type=textjavascriptgtltscriptgtltheadgt
12
Placement Scripts
bull Scripts can be provided locally or remotely accessible JavaScript file using src attribute
lthtmlgtltheadgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=httpsomesitemyOwnJavaScriptjsgtltscriptgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=myOwnSubdirectorymyOwn2ndJavaScriptjsgtltscriptgt
Referencing External JavaScript File
Besides being an object oriented programming language JavaScript is also an event-driven language Lets take a look at what an event is
Whenever the user does something on a Web page whether its loading the page clicking on something or moving the mouse over something its called an event
For JavaScript to recognize an event we need an event handler Event handlers are easy to spot as they usually start with the word on Two commonly used event handlers are onclick and onmouseover
In the case of onmouseover it is attached to an object (lets say a link) on the page As soon as the user puts the mouse pointer over the object that this particular event handler is attached to then whatever you specify in the event handler will happen
The JavaScript event handler is placed inside an HTML tag like so lta href= onclick=windowclose()gtClose this windowltagt
14
What is an Event
onclick - Triggered when the object is clicked onmouseover - Triggered when the mouse moves over the object onmouseout - Triggered when the curser moves off of the object onblur - Triggered when the object is no longer selected (like a form object
or when a window is no longer in front onfocus - Triggered when an object is brought to focus such as bringing a
window in front of another onload - Triggered when the object is done loading onunload - Triggered when the user unloads the page (Loads another page
into the Window) onsubmit - Triggered when the user submits a form onselect - Triggered when the user selects the contents of an object onchange - Triggered when the user changes an object (such as making a
different selection in a form) onerror - Triggered when a JavaScript error is encountered onabort - Triggered when the user stops the page from loading
httpwwww3schoolscomjsjs_events_examplesasp15
Commonly used event handlers
16
lthtmlgt ltbodygt ltscript type=textjavascriptgt
documentwrite(HelloWorld)ltscriptgt ltbodygt lthtmlgt
The above code will produce this output on the HTML page
HelloWorld
17
To insert a JavaScript into an HTML page we use the ltscriptgt tag
The ltscript type=textjavascriptgt and ltscriptgt tells where the JavaScript starts and ends
The script tag encloses any script code you want to use The type attribute alert the browser to the type of script it is
about to deal with it helps in code interpretation
18
The comments around the script are there so that old browsers that donrsquot understand the script tag wonrsquot display the code as text on the page
If the browser can do JavaScript then it will ignore the comments
19
lthtmlgt ltbodygt ltscript type=textjavascriptgt ltscriptgt ltbodygt lthtmlgt
20
The word documentwrite is a standard JavaScript command for writing output to a page
If we had not entered the ltscriptgt tag the browser would have treated the documentwrite(Hello World) command as pure text and just write the entire line on the page
This will be the output
documentwrite(Hello World)
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Java VS JavaScript
Java JavaScript
Sun Microsystems Netscape
Much larger and advanced set of commands
Much smaller and simpler set of commands
Applets distinct from HTML (accessed from HTML pages)
Code integrated with and embedded in HTML
Variable data types must be declared (strong typing)
Variable data types not declared (loose typing)
Compiled on server before execution on client
Interpreted (not compiled) by client
9
JavaScript is written in the same way as HTML in a text editor (Notepad)
JavaScript implementation was quite similar to CSS you can link to outside files (with the file extension js) or write blocks of code into your HTML documents with the ltscriptgt tag
10
How to Put a JavaScript Into an HTML Page
bull JavaScript can be put in the ltheadgt or in the ltbodygt of an HTML documentbull JavaScript functions should be defined in the ltheadgt
bull This ensures that the function is loaded before it is needed
bull JavaScript in the ltbodygt will be executed as the page loads
bull JavaScript can be put in a separate js filebull ltscript src=myJavaScriptFilejsgtltscriptgtbull Put this HTML wherever you would put the actual
JavaScript codebull An external js file lets you use the same JavaScript on
multiple HTML pagesbull The external js file cannot itself contain a ltscriptgt tag
bull JavaScript can be put in HTML form object such as a buttonbull This JavaScript will be executed when the form object is
used
Where Do You Place Scripts
Scripts can either be in the ltheadgt section orltbodygt sectionbull Convention is to place it in the ltheadgt sectionlthtmlgtltheadgtltscript type=textjavascriptgtltscriptgtltheadgt
12
Placement Scripts
bull Scripts can be provided locally or remotely accessible JavaScript file using src attribute
lthtmlgtltheadgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=httpsomesitemyOwnJavaScriptjsgtltscriptgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=myOwnSubdirectorymyOwn2ndJavaScriptjsgtltscriptgt
Referencing External JavaScript File
Besides being an object oriented programming language JavaScript is also an event-driven language Lets take a look at what an event is
Whenever the user does something on a Web page whether its loading the page clicking on something or moving the mouse over something its called an event
For JavaScript to recognize an event we need an event handler Event handlers are easy to spot as they usually start with the word on Two commonly used event handlers are onclick and onmouseover
In the case of onmouseover it is attached to an object (lets say a link) on the page As soon as the user puts the mouse pointer over the object that this particular event handler is attached to then whatever you specify in the event handler will happen
The JavaScript event handler is placed inside an HTML tag like so lta href= onclick=windowclose()gtClose this windowltagt
14
What is an Event
onclick - Triggered when the object is clicked onmouseover - Triggered when the mouse moves over the object onmouseout - Triggered when the curser moves off of the object onblur - Triggered when the object is no longer selected (like a form object
or when a window is no longer in front onfocus - Triggered when an object is brought to focus such as bringing a
window in front of another onload - Triggered when the object is done loading onunload - Triggered when the user unloads the page (Loads another page
into the Window) onsubmit - Triggered when the user submits a form onselect - Triggered when the user selects the contents of an object onchange - Triggered when the user changes an object (such as making a
different selection in a form) onerror - Triggered when a JavaScript error is encountered onabort - Triggered when the user stops the page from loading
httpwwww3schoolscomjsjs_events_examplesasp15
Commonly used event handlers
16
lthtmlgt ltbodygt ltscript type=textjavascriptgt
documentwrite(HelloWorld)ltscriptgt ltbodygt lthtmlgt
The above code will produce this output on the HTML page
HelloWorld
17
To insert a JavaScript into an HTML page we use the ltscriptgt tag
The ltscript type=textjavascriptgt and ltscriptgt tells where the JavaScript starts and ends
The script tag encloses any script code you want to use The type attribute alert the browser to the type of script it is
about to deal with it helps in code interpretation
18
The comments around the script are there so that old browsers that donrsquot understand the script tag wonrsquot display the code as text on the page
If the browser can do JavaScript then it will ignore the comments
19
lthtmlgt ltbodygt ltscript type=textjavascriptgt ltscriptgt ltbodygt lthtmlgt
20
The word documentwrite is a standard JavaScript command for writing output to a page
If we had not entered the ltscriptgt tag the browser would have treated the documentwrite(Hello World) command as pure text and just write the entire line on the page
This will be the output
documentwrite(Hello World)
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
JavaScript is written in the same way as HTML in a text editor (Notepad)
JavaScript implementation was quite similar to CSS you can link to outside files (with the file extension js) or write blocks of code into your HTML documents with the ltscriptgt tag
10
How to Put a JavaScript Into an HTML Page
bull JavaScript can be put in the ltheadgt or in the ltbodygt of an HTML documentbull JavaScript functions should be defined in the ltheadgt
bull This ensures that the function is loaded before it is needed
bull JavaScript in the ltbodygt will be executed as the page loads
bull JavaScript can be put in a separate js filebull ltscript src=myJavaScriptFilejsgtltscriptgtbull Put this HTML wherever you would put the actual
JavaScript codebull An external js file lets you use the same JavaScript on
multiple HTML pagesbull The external js file cannot itself contain a ltscriptgt tag
bull JavaScript can be put in HTML form object such as a buttonbull This JavaScript will be executed when the form object is
used
Where Do You Place Scripts
Scripts can either be in the ltheadgt section orltbodygt sectionbull Convention is to place it in the ltheadgt sectionlthtmlgtltheadgtltscript type=textjavascriptgtltscriptgtltheadgt
12
Placement Scripts
bull Scripts can be provided locally or remotely accessible JavaScript file using src attribute
lthtmlgtltheadgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=httpsomesitemyOwnJavaScriptjsgtltscriptgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=myOwnSubdirectorymyOwn2ndJavaScriptjsgtltscriptgt
Referencing External JavaScript File
Besides being an object oriented programming language JavaScript is also an event-driven language Lets take a look at what an event is
Whenever the user does something on a Web page whether its loading the page clicking on something or moving the mouse over something its called an event
For JavaScript to recognize an event we need an event handler Event handlers are easy to spot as they usually start with the word on Two commonly used event handlers are onclick and onmouseover
In the case of onmouseover it is attached to an object (lets say a link) on the page As soon as the user puts the mouse pointer over the object that this particular event handler is attached to then whatever you specify in the event handler will happen
The JavaScript event handler is placed inside an HTML tag like so lta href= onclick=windowclose()gtClose this windowltagt
14
What is an Event
onclick - Triggered when the object is clicked onmouseover - Triggered when the mouse moves over the object onmouseout - Triggered when the curser moves off of the object onblur - Triggered when the object is no longer selected (like a form object
or when a window is no longer in front onfocus - Triggered when an object is brought to focus such as bringing a
window in front of another onload - Triggered when the object is done loading onunload - Triggered when the user unloads the page (Loads another page
into the Window) onsubmit - Triggered when the user submits a form onselect - Triggered when the user selects the contents of an object onchange - Triggered when the user changes an object (such as making a
different selection in a form) onerror - Triggered when a JavaScript error is encountered onabort - Triggered when the user stops the page from loading
httpwwww3schoolscomjsjs_events_examplesasp15
Commonly used event handlers
16
lthtmlgt ltbodygt ltscript type=textjavascriptgt
documentwrite(HelloWorld)ltscriptgt ltbodygt lthtmlgt
The above code will produce this output on the HTML page
HelloWorld
17
To insert a JavaScript into an HTML page we use the ltscriptgt tag
The ltscript type=textjavascriptgt and ltscriptgt tells where the JavaScript starts and ends
The script tag encloses any script code you want to use The type attribute alert the browser to the type of script it is
about to deal with it helps in code interpretation
18
The comments around the script are there so that old browsers that donrsquot understand the script tag wonrsquot display the code as text on the page
If the browser can do JavaScript then it will ignore the comments
19
lthtmlgt ltbodygt ltscript type=textjavascriptgt ltscriptgt ltbodygt lthtmlgt
20
The word documentwrite is a standard JavaScript command for writing output to a page
If we had not entered the ltscriptgt tag the browser would have treated the documentwrite(Hello World) command as pure text and just write the entire line on the page
This will be the output
documentwrite(Hello World)
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
bull JavaScript can be put in the ltheadgt or in the ltbodygt of an HTML documentbull JavaScript functions should be defined in the ltheadgt
bull This ensures that the function is loaded before it is needed
bull JavaScript in the ltbodygt will be executed as the page loads
bull JavaScript can be put in a separate js filebull ltscript src=myJavaScriptFilejsgtltscriptgtbull Put this HTML wherever you would put the actual
JavaScript codebull An external js file lets you use the same JavaScript on
multiple HTML pagesbull The external js file cannot itself contain a ltscriptgt tag
bull JavaScript can be put in HTML form object such as a buttonbull This JavaScript will be executed when the form object is
used
Where Do You Place Scripts
Scripts can either be in the ltheadgt section orltbodygt sectionbull Convention is to place it in the ltheadgt sectionlthtmlgtltheadgtltscript type=textjavascriptgtltscriptgtltheadgt
12
Placement Scripts
bull Scripts can be provided locally or remotely accessible JavaScript file using src attribute
lthtmlgtltheadgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=httpsomesitemyOwnJavaScriptjsgtltscriptgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=myOwnSubdirectorymyOwn2ndJavaScriptjsgtltscriptgt
Referencing External JavaScript File
Besides being an object oriented programming language JavaScript is also an event-driven language Lets take a look at what an event is
Whenever the user does something on a Web page whether its loading the page clicking on something or moving the mouse over something its called an event
For JavaScript to recognize an event we need an event handler Event handlers are easy to spot as they usually start with the word on Two commonly used event handlers are onclick and onmouseover
In the case of onmouseover it is attached to an object (lets say a link) on the page As soon as the user puts the mouse pointer over the object that this particular event handler is attached to then whatever you specify in the event handler will happen
The JavaScript event handler is placed inside an HTML tag like so lta href= onclick=windowclose()gtClose this windowltagt
14
What is an Event
onclick - Triggered when the object is clicked onmouseover - Triggered when the mouse moves over the object onmouseout - Triggered when the curser moves off of the object onblur - Triggered when the object is no longer selected (like a form object
or when a window is no longer in front onfocus - Triggered when an object is brought to focus such as bringing a
window in front of another onload - Triggered when the object is done loading onunload - Triggered when the user unloads the page (Loads another page
into the Window) onsubmit - Triggered when the user submits a form onselect - Triggered when the user selects the contents of an object onchange - Triggered when the user changes an object (such as making a
different selection in a form) onerror - Triggered when a JavaScript error is encountered onabort - Triggered when the user stops the page from loading
httpwwww3schoolscomjsjs_events_examplesasp15
Commonly used event handlers
16
lthtmlgt ltbodygt ltscript type=textjavascriptgt
documentwrite(HelloWorld)ltscriptgt ltbodygt lthtmlgt
The above code will produce this output on the HTML page
HelloWorld
17
To insert a JavaScript into an HTML page we use the ltscriptgt tag
The ltscript type=textjavascriptgt and ltscriptgt tells where the JavaScript starts and ends
The script tag encloses any script code you want to use The type attribute alert the browser to the type of script it is
about to deal with it helps in code interpretation
18
The comments around the script are there so that old browsers that donrsquot understand the script tag wonrsquot display the code as text on the page
If the browser can do JavaScript then it will ignore the comments
19
lthtmlgt ltbodygt ltscript type=textjavascriptgt ltscriptgt ltbodygt lthtmlgt
20
The word documentwrite is a standard JavaScript command for writing output to a page
If we had not entered the ltscriptgt tag the browser would have treated the documentwrite(Hello World) command as pure text and just write the entire line on the page
This will be the output
documentwrite(Hello World)
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Scripts can either be in the ltheadgt section orltbodygt sectionbull Convention is to place it in the ltheadgt sectionlthtmlgtltheadgtltscript type=textjavascriptgtltscriptgtltheadgt
12
Placement Scripts
bull Scripts can be provided locally or remotely accessible JavaScript file using src attribute
lthtmlgtltheadgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=httpsomesitemyOwnJavaScriptjsgtltscriptgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=myOwnSubdirectorymyOwn2ndJavaScriptjsgtltscriptgt
Referencing External JavaScript File
Besides being an object oriented programming language JavaScript is also an event-driven language Lets take a look at what an event is
Whenever the user does something on a Web page whether its loading the page clicking on something or moving the mouse over something its called an event
For JavaScript to recognize an event we need an event handler Event handlers are easy to spot as they usually start with the word on Two commonly used event handlers are onclick and onmouseover
In the case of onmouseover it is attached to an object (lets say a link) on the page As soon as the user puts the mouse pointer over the object that this particular event handler is attached to then whatever you specify in the event handler will happen
The JavaScript event handler is placed inside an HTML tag like so lta href= onclick=windowclose()gtClose this windowltagt
14
What is an Event
onclick - Triggered when the object is clicked onmouseover - Triggered when the mouse moves over the object onmouseout - Triggered when the curser moves off of the object onblur - Triggered when the object is no longer selected (like a form object
or when a window is no longer in front onfocus - Triggered when an object is brought to focus such as bringing a
window in front of another onload - Triggered when the object is done loading onunload - Triggered when the user unloads the page (Loads another page
into the Window) onsubmit - Triggered when the user submits a form onselect - Triggered when the user selects the contents of an object onchange - Triggered when the user changes an object (such as making a
different selection in a form) onerror - Triggered when a JavaScript error is encountered onabort - Triggered when the user stops the page from loading
httpwwww3schoolscomjsjs_events_examplesasp15
Commonly used event handlers
16
lthtmlgt ltbodygt ltscript type=textjavascriptgt
documentwrite(HelloWorld)ltscriptgt ltbodygt lthtmlgt
The above code will produce this output on the HTML page
HelloWorld
17
To insert a JavaScript into an HTML page we use the ltscriptgt tag
The ltscript type=textjavascriptgt and ltscriptgt tells where the JavaScript starts and ends
The script tag encloses any script code you want to use The type attribute alert the browser to the type of script it is
about to deal with it helps in code interpretation
18
The comments around the script are there so that old browsers that donrsquot understand the script tag wonrsquot display the code as text on the page
If the browser can do JavaScript then it will ignore the comments
19
lthtmlgt ltbodygt ltscript type=textjavascriptgt ltscriptgt ltbodygt lthtmlgt
20
The word documentwrite is a standard JavaScript command for writing output to a page
If we had not entered the ltscriptgt tag the browser would have treated the documentwrite(Hello World) command as pure text and just write the entire line on the page
This will be the output
documentwrite(Hello World)
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
bull Scripts can be provided locally or remotely accessible JavaScript file using src attribute
lthtmlgtltheadgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=httpsomesitemyOwnJavaScriptjsgtltscriptgtltscript language=JavaScriptldquo type=textjavascriptldquo
src=myOwnSubdirectorymyOwn2ndJavaScriptjsgtltscriptgt
Referencing External JavaScript File
Besides being an object oriented programming language JavaScript is also an event-driven language Lets take a look at what an event is
Whenever the user does something on a Web page whether its loading the page clicking on something or moving the mouse over something its called an event
For JavaScript to recognize an event we need an event handler Event handlers are easy to spot as they usually start with the word on Two commonly used event handlers are onclick and onmouseover
In the case of onmouseover it is attached to an object (lets say a link) on the page As soon as the user puts the mouse pointer over the object that this particular event handler is attached to then whatever you specify in the event handler will happen
The JavaScript event handler is placed inside an HTML tag like so lta href= onclick=windowclose()gtClose this windowltagt
14
What is an Event
onclick - Triggered when the object is clicked onmouseover - Triggered when the mouse moves over the object onmouseout - Triggered when the curser moves off of the object onblur - Triggered when the object is no longer selected (like a form object
or when a window is no longer in front onfocus - Triggered when an object is brought to focus such as bringing a
window in front of another onload - Triggered when the object is done loading onunload - Triggered when the user unloads the page (Loads another page
into the Window) onsubmit - Triggered when the user submits a form onselect - Triggered when the user selects the contents of an object onchange - Triggered when the user changes an object (such as making a
different selection in a form) onerror - Triggered when a JavaScript error is encountered onabort - Triggered when the user stops the page from loading
httpwwww3schoolscomjsjs_events_examplesasp15
Commonly used event handlers
16
lthtmlgt ltbodygt ltscript type=textjavascriptgt
documentwrite(HelloWorld)ltscriptgt ltbodygt lthtmlgt
The above code will produce this output on the HTML page
HelloWorld
17
To insert a JavaScript into an HTML page we use the ltscriptgt tag
The ltscript type=textjavascriptgt and ltscriptgt tells where the JavaScript starts and ends
The script tag encloses any script code you want to use The type attribute alert the browser to the type of script it is
about to deal with it helps in code interpretation
18
The comments around the script are there so that old browsers that donrsquot understand the script tag wonrsquot display the code as text on the page
If the browser can do JavaScript then it will ignore the comments
19
lthtmlgt ltbodygt ltscript type=textjavascriptgt ltscriptgt ltbodygt lthtmlgt
20
The word documentwrite is a standard JavaScript command for writing output to a page
If we had not entered the ltscriptgt tag the browser would have treated the documentwrite(Hello World) command as pure text and just write the entire line on the page
This will be the output
documentwrite(Hello World)
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Besides being an object oriented programming language JavaScript is also an event-driven language Lets take a look at what an event is
Whenever the user does something on a Web page whether its loading the page clicking on something or moving the mouse over something its called an event
For JavaScript to recognize an event we need an event handler Event handlers are easy to spot as they usually start with the word on Two commonly used event handlers are onclick and onmouseover
In the case of onmouseover it is attached to an object (lets say a link) on the page As soon as the user puts the mouse pointer over the object that this particular event handler is attached to then whatever you specify in the event handler will happen
The JavaScript event handler is placed inside an HTML tag like so lta href= onclick=windowclose()gtClose this windowltagt
14
What is an Event
onclick - Triggered when the object is clicked onmouseover - Triggered when the mouse moves over the object onmouseout - Triggered when the curser moves off of the object onblur - Triggered when the object is no longer selected (like a form object
or when a window is no longer in front onfocus - Triggered when an object is brought to focus such as bringing a
window in front of another onload - Triggered when the object is done loading onunload - Triggered when the user unloads the page (Loads another page
into the Window) onsubmit - Triggered when the user submits a form onselect - Triggered when the user selects the contents of an object onchange - Triggered when the user changes an object (such as making a
different selection in a form) onerror - Triggered when a JavaScript error is encountered onabort - Triggered when the user stops the page from loading
httpwwww3schoolscomjsjs_events_examplesasp15
Commonly used event handlers
16
lthtmlgt ltbodygt ltscript type=textjavascriptgt
documentwrite(HelloWorld)ltscriptgt ltbodygt lthtmlgt
The above code will produce this output on the HTML page
HelloWorld
17
To insert a JavaScript into an HTML page we use the ltscriptgt tag
The ltscript type=textjavascriptgt and ltscriptgt tells where the JavaScript starts and ends
The script tag encloses any script code you want to use The type attribute alert the browser to the type of script it is
about to deal with it helps in code interpretation
18
The comments around the script are there so that old browsers that donrsquot understand the script tag wonrsquot display the code as text on the page
If the browser can do JavaScript then it will ignore the comments
19
lthtmlgt ltbodygt ltscript type=textjavascriptgt ltscriptgt ltbodygt lthtmlgt
20
The word documentwrite is a standard JavaScript command for writing output to a page
If we had not entered the ltscriptgt tag the browser would have treated the documentwrite(Hello World) command as pure text and just write the entire line on the page
This will be the output
documentwrite(Hello World)
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
onclick - Triggered when the object is clicked onmouseover - Triggered when the mouse moves over the object onmouseout - Triggered when the curser moves off of the object onblur - Triggered when the object is no longer selected (like a form object
or when a window is no longer in front onfocus - Triggered when an object is brought to focus such as bringing a
window in front of another onload - Triggered when the object is done loading onunload - Triggered when the user unloads the page (Loads another page
into the Window) onsubmit - Triggered when the user submits a form onselect - Triggered when the user selects the contents of an object onchange - Triggered when the user changes an object (such as making a
different selection in a form) onerror - Triggered when a JavaScript error is encountered onabort - Triggered when the user stops the page from loading
httpwwww3schoolscomjsjs_events_examplesasp15
Commonly used event handlers
16
lthtmlgt ltbodygt ltscript type=textjavascriptgt
documentwrite(HelloWorld)ltscriptgt ltbodygt lthtmlgt
The above code will produce this output on the HTML page
HelloWorld
17
To insert a JavaScript into an HTML page we use the ltscriptgt tag
The ltscript type=textjavascriptgt and ltscriptgt tells where the JavaScript starts and ends
The script tag encloses any script code you want to use The type attribute alert the browser to the type of script it is
about to deal with it helps in code interpretation
18
The comments around the script are there so that old browsers that donrsquot understand the script tag wonrsquot display the code as text on the page
If the browser can do JavaScript then it will ignore the comments
19
lthtmlgt ltbodygt ltscript type=textjavascriptgt ltscriptgt ltbodygt lthtmlgt
20
The word documentwrite is a standard JavaScript command for writing output to a page
If we had not entered the ltscriptgt tag the browser would have treated the documentwrite(Hello World) command as pure text and just write the entire line on the page
This will be the output
documentwrite(Hello World)
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
16
lthtmlgt ltbodygt ltscript type=textjavascriptgt
documentwrite(HelloWorld)ltscriptgt ltbodygt lthtmlgt
The above code will produce this output on the HTML page
HelloWorld
17
To insert a JavaScript into an HTML page we use the ltscriptgt tag
The ltscript type=textjavascriptgt and ltscriptgt tells where the JavaScript starts and ends
The script tag encloses any script code you want to use The type attribute alert the browser to the type of script it is
about to deal with it helps in code interpretation
18
The comments around the script are there so that old browsers that donrsquot understand the script tag wonrsquot display the code as text on the page
If the browser can do JavaScript then it will ignore the comments
19
lthtmlgt ltbodygt ltscript type=textjavascriptgt ltscriptgt ltbodygt lthtmlgt
20
The word documentwrite is a standard JavaScript command for writing output to a page
If we had not entered the ltscriptgt tag the browser would have treated the documentwrite(Hello World) command as pure text and just write the entire line on the page
This will be the output
documentwrite(Hello World)
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
17
To insert a JavaScript into an HTML page we use the ltscriptgt tag
The ltscript type=textjavascriptgt and ltscriptgt tells where the JavaScript starts and ends
The script tag encloses any script code you want to use The type attribute alert the browser to the type of script it is
about to deal with it helps in code interpretation
18
The comments around the script are there so that old browsers that donrsquot understand the script tag wonrsquot display the code as text on the page
If the browser can do JavaScript then it will ignore the comments
19
lthtmlgt ltbodygt ltscript type=textjavascriptgt ltscriptgt ltbodygt lthtmlgt
20
The word documentwrite is a standard JavaScript command for writing output to a page
If we had not entered the ltscriptgt tag the browser would have treated the documentwrite(Hello World) command as pure text and just write the entire line on the page
This will be the output
documentwrite(Hello World)
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
18
The comments around the script are there so that old browsers that donrsquot understand the script tag wonrsquot display the code as text on the page
If the browser can do JavaScript then it will ignore the comments
19
lthtmlgt ltbodygt ltscript type=textjavascriptgt ltscriptgt ltbodygt lthtmlgt
20
The word documentwrite is a standard JavaScript command for writing output to a page
If we had not entered the ltscriptgt tag the browser would have treated the documentwrite(Hello World) command as pure text and just write the entire line on the page
This will be the output
documentwrite(Hello World)
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
19
lthtmlgt ltbodygt ltscript type=textjavascriptgt ltscriptgt ltbodygt lthtmlgt
20
The word documentwrite is a standard JavaScript command for writing output to a page
If we had not entered the ltscriptgt tag the browser would have treated the documentwrite(Hello World) command as pure text and just write the entire line on the page
This will be the output
documentwrite(Hello World)
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
20
The word documentwrite is a standard JavaScript command for writing output to a page
If we had not entered the ltscriptgt tag the browser would have treated the documentwrite(Hello World) command as pure text and just write the entire line on the page
This will be the output
documentwrite(Hello World)
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
21
You can place an unlimited number of scripts in your document so that you can have scripts in both the body and the head section
lthtmlgtltheadgtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltheadgtltbodygtltscript type=ldquotextjavascriptrdquogthelliphellipltscriptgtltbodygt
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
22
External scripts
To import scripts from external JavaScript files save the code in the text file with the js extension without the script tags and comment
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
23
A simple example for external scripts
Save as mainhtml
Save as hellojs
lthtmlgtltbodygtltscript language=javascript type=textjavascriptsrc=hellojsgtltscriptgt ltbodygtlthtmlgt
var hello = Hello Worlddocumentwrite(hello)
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
24
Output
Hello World
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
25
ltnoscriptgt tag
The noscript element is used to define an alternate content (text) if a script is NOT executed
This tag is used for browsers that recognizes the ltscriptgt tag but does not support the script in it
If a browser supports scripting it will not display the text in the noscript element
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
26
Example
ltnoscriptgtYour browser does not support JavaScriptltnoscriptgt
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
27
lthtmlgt
ltheadgtltbodygtltscript type=textjavascriptgtlt--documentwrite(Hello World)--gtltscriptgtltnoscriptgtYour browser does not support JavaScriptltnoscriptgtltbodygt ltheadgtlthtmlgt
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
bull JavaScript has three ldquoprimitiverdquo types number string and boolean
bull Numbers are always stored as floating-point valuesbull Hexadecimal numbers begin with 0xbull Some platforms treat 0123 as octal others treat it as decimal
bull Strings may be enclosed in single quotes or double quotesbull Strings can contains n (newline) (double quote) etc
bull Booleans are either true or falsebull 0 0 empty strings undefined null and NaN are false
other values are true
Primitive Datatypes
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
bull You create a variable with or without the ldquovarrdquo statement
var num = ldquo1rdquo var name = ldquoKaushalrdquo var phone = ldquo123-456-7890rdquo
bull Variables names must begin with a letter or underscorebull Variable names are case-sensitive bull Variables are untyped (they can hold values of any
type)bull The word var is optional (but itrsquos good style to use it)bull Variables declared within a function are local to that
function (accessible only within that function)bull Variables declared outside a function are global
(accessible from anywhere on the page)
JavaScript Variable
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
bull Comments are as in C or Javabull Single Line Comment bull Paragraph Comment hellip
bull Javarsquos javadoc comments are treated just the same as comments they have no special meaning in JavaScript
Comments
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
31
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
32
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
33
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
bull Alert boxgt User will have to click OK to proceedgt alert(sometext)bull Confirm boxgt User will have to click either OK or Cancel to proceedgt confirm(sometext)bull Prompt boxgt User will have to click either OK or Cancel to proceed afterentering an input valuegt prompt(sometextdefaultvalue)
34
JavaScript Popup Boxes
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Write a program by putting all of the alert statements into the ltheadgt section of the page This way they load up before that page even displays any data
Yourcode should have the following info ltscript language=JavaScript type=textjavascriptgt
lt--alert(This is an example of how to misuse the JavaScript Alert box)alert(Each time you click ok another one pops up)alert(You cant even close your browser window until the demonstration is done)alert(Isnt this annoying)alert(This could potentially go on forever)alert(Ok well stop)alert(But first you have to promise to never do this)alert(You have to promise)alert(Are you sure your fingers arent crossed)alert(Hey Your toes too)alert(OK we believe you)alert(This concludes annoying JavaScript test number 1)--gtltscriptgt
Follow up the above code with another little ltbodygt script with another write() method to give you a message
documentwrite(wasnt that annoying)
35
Practice
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Scripts that will write out text or HTML code out onto the page must be placed in its ltbodygt section
To write out text or HTML to a page we use the document objects write() method
JavaScript statements should always end with a semicolon () Scripts placed inside HTML tags write out text the same as if
they were not written out by JavaScript Alert boxes can be used to grab the viewers attention When placing an event handler in an anchor you can
use href= as the link The return false statement prevents the browser from acting
on the link contained in the href attribute You can also use javascript as a link for an event handler in
which case you dont need the return false statement Escaping a character using the backslash character () tells the
browser to ignore the character that immediately follows it Alert() is a method of the window object
36
Your First Scripts Summary
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
bull JavaScript allows you to declare and use variables tostore valuesbull How to assign a name to a variablendash Include uppercase and lowercase lettersndash Digits from 0 through 9ndash The underscore _ and the dollar sign $ndash No space and punctuation charactersndash First character must be alphabetic letter or underscore ndash Case‐sensitivendash No reserved words or keywords
37
Variables
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Variables Variables are very important for any kind of programming Without
them complex scripts would never be possible When used correctly they can also save you a lot of typing The ability to effectively use variables is what separates a good programmer from a sloppy one
What is a Variable The best way to think of a variable is as a container With a
conventional container you use it to put things in Variables work in the same way However instead of putting things into them we assign them values So we could also say that variables contain values
Defining Variables When you first tell JavaScript about a variable it is
call declaring it The best way to declare a variable is to use the word var before it
A variable can be defined by assigning it a value For example var my_number = 10
38
Variables
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
39
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
You can also declare a variable without assigning it a value like so
var my_number It is usually a good programming practice
to declare all of your variables at the beginning of the script You dont necessarily need to assign any values to them but this way they have been declared or initialized This is kind of like laying out all the tools you might need to work on your car before you start working This also lets you see at a glance all of the variables you are dealing with in the script
40
Variable Declarations
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Heres an example var first_name = betty Now the variable first_name has the value of betty
Whenever you will be re-using any kind of text especially long bits of text it can be useful to make it into a variable For example
documentwrite(This is some text that will be written out several times within the page)
Instead of having to do this again and again you could assign the text (also called a text string) to a variable
var my_text = This is some text that will be written out several times within the page
documentwrite(my_text) Now this text string can be written out many times using only
the variable my_text This may seem a little pointless right now but as you start writing larger and larger scripts this will be a very good habit
41
Variables can also have text values
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
42
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
About the above example The text for the variable is enclosed in
quotes For JavaScript to assign text to a variable it must be enclosed in quotes These can be either single or double quotes
When we refer to the variable my_text inside the write() method we dont use the quotes If we were to enclose my_text inside quotes then the words my_text would be written out to the document When referring to a variable dont enclose it in quotes
43
Observations
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Sometimes it can seem a little confusing as to when you should use var and when you dont need to So lets clear this up a bit
You dont need to use var for the same variable more than once you only need it when you first declare that variable For example lets say you declare a variable without assigning it a value early in your script
var my_name Later on in your script you may want to assign my_name a
value Since you have already declared the variable at the beginning of your script you dont need to use var again
my_name = mortimer Note You may notice when looking at some scripts that people
dont always use var when declaring variables This will probably work much of the time but to be on the safe side I would recommend that you should always declare your variables with var
44
To var or not to var
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
A variable can be thought of as a container that you put things into Variables are assigned values The first time you use a variable in a script it is called declaring or
initializing it Variables can have text string numeric or boolean values Text string values must be enclosed in quotes The value of a variable can be changed at any time in the script It is a good idea to give your variables descriptive names Variable names cannot start with numbers contain spaces or
punctuation They also cannot use words reserved by JavaScript JavaScript variable names are case sensitive When you first declare a variable use the word var in front of it var only needs to be used once for a variable
45
Variables Summary
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
JavaScript allows the same variable to contain different typesof data valuesbull Primitive data typesndash Number integer amp floating‐point numbersndash Boolean logical values ldquotruerdquo or ldquofalserdquondash String a sequence of alphanumeric charactersbull Composite data types (or Complex data types)ndash Object a named collection of datandash Array a sequence of valuesbull Special data typesndash Null an initial value is assignedndash Undefined the variable has been created but not yet assigned a value 46
Data Types
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
bull It is an important part of any programminglanguage for doing arithmetic calculationsbull JavaScript supportsndash Integers A positive or negative number with nodecimal placesbull Ranged from ndash253 to 253ndash Floating‐point numbers usually written inexponential notationbull 31415hellip 20e11
47
Numeric Data Types
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
bullA string variable can store a sequence of alphanumeric characters spaces and special charactersbull String can also be enclosed in single quotationmarks (lsquo) or in double quotation marks (ldquo)bull What is the data type of ldquo100rdquondash String but not number typebull Pay attention to the special characters
48
Strings
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
49
Strings example
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
bull An object is a thing anything just as things inthe real worldndash Eg (cars dogs money books hellip)bull In the web browser objects are the browserwindow itself forms buttons text boxes hellipbull Methods are things that objects can dondash Cars can move dogs can barkndash Window object can alert the user ldquoalert()rdquobull All objects have propertiesndash Cars have wheels dogs have furndash Browser has a name and version number
50
What is an Object
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types
We will only look at the built-in JavaScript objects and how they are used The next slides will explain each built-in JavaScript object in detail
Remember that an object is just a special kind of data An object has properties and methods
51
Object in JavaScript
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
52
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram The window itself is an object that have document in it In document it has another object such as images and forms Each of these objects have its own properties and methods
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
53
Object in JavaScript - properties
bullProperties are the values associated with an object
bullBelow examples shows how to access length property of document object to return the number of characters in a string
ltscript type=textjavascriptgt
var txt=Hello Worldldquodocumentwrite(txtlength)
ltscriptgt
bullThe output of the code above will be12 ( H e l l o [space] W o r l d )
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
54
Object in JavaScript - methods
bullMethods are the actions that can be performed on objects
bullIn the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters
ltscript type=textjavascriptgtvar str=Hello world documentwrite(strtoUpperCase())
ltscriptgt
bullThe output of the code above will be
HELLO WORLD
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Object Properties Methods
Window defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Frame defaultStatus frames opener parent scroll self status top window
Alert blur close confirm focus open prompt clearTimeout setTimeout
Location Hash host hostname href pathname por protocol search
Reload replace
History Length forward go Back
Navigator appCodeName appName appVersion mimeTypes plugins userAgents
javaEnabled
Documents alinkColor anchors applets ares bgColor cookie fgColor forms images lastModified linkColor links location referrer title vlinkColor
Clear close open write writeln
Image Border complete heigth hspace lowwsrc vspace width
None
Form Action elements encoding FileUpload method name target
Submit reset
Text defaultValue name type value Focus blur select
55
The most commonly used JavaScript objects
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Objects Properties Methods
Array Length Join reverse sort xx
Date None getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC
String Length Prototype Anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup
toLowerCasetoUpperCase 56
The most commonly used Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
String Object Date Object Array Object Math Object Boolean Object
57
Built-in JavaScript Objects
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
The String object is used to manipulate a stored piece of text
The following example uses the length property of the String object to find the length of a string
ltscript type=textjavascriptgt
var txt=Hello Worldrdquodocumentwrite(txtlength)
ltscriptgt
The above code will result in following output 12
58
Built-in JavaScript Objects - String
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
The Date object is used to work with dates and times Example below shows how to use Date() method to get todayrsquos
date ltscript type=textjavascriptgt
documentwrite(Date())ltscriptgt
The output will beMon June 09 155151 2012
59
Built-in JavaScript Objects - Date
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
This 2nd example shows how to use getTime() method to calculate years since 1970
ltscript type=textjavascriptgtvar minutes = 100060var hours = minutes60var days = hours24var years = days365var d = new Date()var t = dgetTime()var y = tyears
documentwrite(Its been + y + years since 19700101)ltscriptgt
The output will be Its been 3786941401639396 years since 19700101
60
Built-in JavaScript Objects - Date
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
The Array object is used to store a set of values in a single variable name
1 We create a new Array by assigning it to a new keyword myArrayvar mycars=new Array() mycars[0]=ldquoLotus mycars[1]=Volvo mycars[2]=BMW ORvar mycars=new Array(SaabVolvoBMW)
61
Built-in JavaScript Objects - Array
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
2 We can refer to a particular element in an array by referring to the name of the array and the index number The index
number starts at 0 The following code line
documentwrite(mycars[0]) will result in the following output
Lotus
3 To modify a value in an existing array just add a new value to the array with a specified index number and then try to access it
mycars[0]=ldquoLexusrdquodocumentwrite(mycars[0])
will result in the following outputLexus
62
Built-in JavaScript Objects - Array
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Functions are a great way to help you write more economical JavaScript code Scripts that make good use of functions are capable of doing far more than scripts that dont As you will see in this lecture functions are a great thing to know how to use
63
Functions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
bull A function is a block of organized reusablecode (a set of statements) for performing asingle or related actionbull Begins with keyword ldquofunctionrdquo and thefunction name and ldquo( hellip)rdquobull Inside the parenthesesndash We can pass parameters to the functionndash Eg function myfuc(arg1 arg2) hellipndash Built‐in and user‐defined functions
64
Functions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
bull Functions provided by the language and you cannot changethem to suit your needsbull Some of the built‐in functions in JavaScript are shown herendash eval ‐ eval(expr)bull eval evaluates the expression or statementsndash isFinitebull Determines if a number is finitendash isNaNbull Determines whether a value is ldquoNot a Numberrdquondash parseIntbull Converts string literals to integers no number 1048774NaNndash parseFloat
bull Finds a floating‐point value at the beginning of a string65
Built‐In Functions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
A function is basically like a bit of self contained code within a script In form it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces
A function can either carry out an action (or set of actions) return a value or both Good functions can be re-used over and over again They can be thought of as building blocks that can be used in numerous other scripts
Functions take the following form
function myFunction(parameters) statements contained within the function
66
Functions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
bull For some functionality you cannot achieve byonly using the built‐in functionsbull You can define a function as followsfunction ltfunction_namegt (parameters) code segments
67
User‐Defined Functions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Here is an example of a script that checked for an symbol and returned either a -1 or its position in the string
function checkEmail() var email_addy = prompt(Please enter your email
address) var is_email = email_addyindexOf() alert(is_email)
Notice that the function contents are indented the
same way that we indented conditionals and loops earlier This is good coding practice as it makes your code easier to read and understand
68
Example
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
A function will only run when it is asked to This is referred to as calling a function Functions are commonly called from within event handlers (remember those) but functions can also be called from other areas of the script including other functions
69
Calling Functions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
A function is called within a script by writing its name followed by parentheses with or without parameters Letrsquos look at functions without parameters for simplicitys sake
alert(we need to check to see where the symbol is at)
Call the functioncheckEmail()
If we are assuming this is a separate script from the one above (and we are) then we dont need to include the function itself in this script It can be called from anywhere on the page Once again not only can a function be called from inside a script it can also be called from inside another function
70
Calling a Function From a Script
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
One of the more common ways to call a function is with an event handler Such an event handler could look something like this
lta href = onclick = swapImage() return falsegtClick to see an image changeltagt
In this case the event handler onclick will call the function swapImage()
A function can also be called without user interaction when the page loads by using the onload event handler
ltbody onload = loadImages()gt
71
Calling a Function With an Event Handler
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
You can pass variables to functions from other areas of the page This is done using the functions parameters Heres how this is done Lets start with the event handler
lta href = onclick=varPassTest(Tom Dick Harry) return falsegtClick to pass some variables to a functionltagt
As you can see we placed three text strings separated by commas between the parentheses of the function call Heres the function
function varPassTest(name1 name2 name3) alert(name1 + name2 + name3) When you click on the link that contains the event handler
the three values are passed to the function The function itself has three parameters name1 name2
and name3 The only thing contained within the function itself is an alert box
that will display all three variables (Note you dont need to initialize these variables with the var statement as the are already automatically initialized when used this way )
72
Passing Variables
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input The script inside the ltbodygt of the document will ask you for the number and print out the result The function is contained in the ltheadgt section
Here is the body script
Prompt the user for a numbervar initial_number = prompt(Please type in a number)
Call the function and pass it initial_number for processingfixed_number = addDollar(initial_number)
take the number the function returned and write it outdocumentwrite(This is your number converted to a dollar amount + fixed_number)
Here is the function in the ltheadgt scriptfunction addDollar(num) add the dollar sign before the number and 00 after
new_number = $ + num + 00
return the num variable back out of the function return new_number
73
Simple function
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Explanation about what happens in these scripts The user is prompted for a number which is assigned to
the initial_number variable initial_number gets passed to the function addDollar Once in the function the value of initial_number is assigned to the
functions parameter num new_number is given the value of num with a dollar ($) character
before it and a period and two dots after The statement return new_number returns the value
of new_number back out of the function The returned variable is assigned to fixed_number fixed_number is printed out on the screen This function we just created can be used again and again in this
document and in turn re-used later on in other scripts and documents if you like It is singular in its purpose which is to turn any number passed to it into a dollar amount
74
Explanation
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
The Math object allows you to perform common mathematical tasks
The Math object includes several mathematical values and functions You do not need to define the Math object before using it
75
Built-in JavaScript Objects - Math
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object
These are E PI square root of 2 square root of 12 natural log of 2 natural log of 10 base-2 log of E and base-10 log of E
You may reference these values from your JavaScript like this
MathE MathPI MathSQRT2 MathSQRT1_2 MathLN2 MathLN10 MathLOG2E MathLOG10E
76
Built-in JavaScript Objects ndash Math - values
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available
The following example uses the round() method of the Math object to round a number to the nearest integer
documentwrite(Mathround(47)) The code above will result in the following output
5
77
Built-in JavaScript Objects ndash Math - methods
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
The Boolean object is an object wrapper for a Boolean value
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false)
We define a Boolean object with the new keyword The following code line defines a Boolean object called myBoolean
var myBoolean=new Boolean()
78
Built-in JavaScript Objects - Boolean
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
If the Boolean object has no initial value or if it is 0 -0 null false undefined or NaN the object is set to false Otherwise it is true (even with the string false)
Example of Boolean object with initial value of falsevar myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean() var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of truevar myBoolean=new Boolean(true) var myBoolean=new Boolean(true) var myBoolean=new Boolean(false) var myBoolean=new Boolean(Richard)
79
Built-in JavaScript Objects - Boolean
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
JavaScript deals with objects One good way to think about this is to compare it to real life objects Lets take a car for example A car is an object The car has wheels and these wheels each have tires If we were to write out these objects in dot syntax it would look like this
carwheelstires Besides tires car wheels also have hubcaps (ok not all cars
but lets assume so) So these objects can be written out this way
carwheelshubcaps Going back to the tires we can take this a step further The
cars tires have tread So this can be written out in dot syntax like this
carwheelstirestread Therefore it would obviously be incorrect to write
carswheelshubcapstread as hubcaps dont have tread but tires do Get it Good
80
Objects
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
These objects can also have properties By changing the properties of an object you change the object For example the color of the hubcaps on the car are gray This can be written out as
carwheelshubcapscolourgrey If we wanted to change the colour of our cars hubcaps
we could do so by writing carwheelshubcapscoloursilver Ok we cant to that to a car (if only it were that easy)
but we can do this in JavaScript As we will see One other thing to note is that many of our cars
properties (wheels hubcaps etc) are also objects in their own right which can have their own properties
81
OBJECTS
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
1 Create a direct instance of an object2 Create template of an object
82
How to create an object
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
83
Object
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
1 Direct Instance
Add a few properties to the birdBirdObj=new Object()
BirdObjname=ldquoMorningBirdldquoBirdObjage=2 BirdObjeyecolor=ldquogreen
Add methods to the birdBirdObjfly = flyBirdObjeat = eatBirfObjBreath = breath
84
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
2 Create Template to the object
function Bird(nameageeyecolor) thisname=name
thisage=age thiseyecolor=eyecolor
When you have template then you can create new instance of the object
myBird= new Bird (ldquoParrotrdquo 2 ldquobluerdquo)
85
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
You can also add some methods to the bird object This is also done inside the template
function Bird(nameageeyecolor) thisname=name
thisage=agethiseyecolor=eyecolor
thishabitat = habitat new method
That methods are just functions attached to objects Then we will have to write the habitat() function
function habitat(new_habitat)
thishabitat=new_habitat
Eg myBirdhabitat(ldquoPondrdquo)
86
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Cookies are variables that can be stored on a users computer and be picked up by any other web pages in the correct domain and path Cookies are set to expire after a certain length of time They are limited to storing string values only
Be warned that many users (including me) will not permit cookies on their computers Do not make your web sites rely on them
The reason for this is that many web sites only use cookies as part of advert tracing systems which they use to track your movement around the Internet
I would not want anyone to follow me around a city while I was shopping taking notes of every shop I visit as that would be an invasion of my privacy Many people feel the same applies to the Internet You may find it helps to firstly display a message saying what you are going to use the cookie for for example to store a username and password for the next time they visit the site
87
Cookies
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Some browsers will have a limit to how many cookies they can store usually 300 cookies or more of which there may be 20 cookies per domain name
A total of 4 KB (after encoding) of cookies can be stored for any domain or path
The documentcookie object is a string representation of all cookies available to the current web page
Thedocumentcookie object is somewhat unusual in that when you assign string values to it it does not become the value that you assign to it
Instead it takes a part of that value and appends its current value to that so making a string containing several pairs of variableName=variableValue
88
Cookies
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Cookies are created or modified by assigning a name=value pair to the documentcookie object
documentcookie = cookieString
The cookieString is more than just a single value As well as a value it can contain other information such as when you want the cookie to expire and what file paths it should apply to
Any of these values that you want to specify should be put together in a string as keyword=value keyword=valueetc and assigned as a single string to documentcookie Only the cookie name and value are required all other values are optional
89
Creating modifying and deleting cookies
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
cookieName and cookieValue are strings and must be URL encoded They can contain any characters To URL encode a cookie name or value you can use the escape method
Unfortunately this cannot cope with unicode characters Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode but if you use this you will lose support for older browsers This must be written in full
The DatetoGMTString() method can return dates in the correct format for you For examplevar theDate = new Date() var oneYearLater = new Date( theDategetTime() + 31536000000 ) var expiryDate = oneYearLatertoGMTString()
Once the specified date is reached the cookie expires and is deleted If expires is not specified the cookie will be deleted when the browser is closed If expires is set to a date in the past the cookie is deleted immediately
This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie)
90
Cookies
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
The HTML DOM defines a standard set of objects for HTML and a standard way to access and manipulate HTML documents
All HTML elements along with their containing text and attributes can be accessed through the DOM
The contents can be modified or deleted and new elements can be created
JavaScript uses the HTML Document Object Model to manipulate HTML
Levels of the DOM are dot-separated in the syntax
91
DOM What is it
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
DOM Specification
ldquoa platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content structure and style of documents hellip [DOM] provides a standard set of objects for representing HTML and XML documents a standard model of how these objects can be combined and a standard interface for accessing and manipulating themrdquo
92
DOM What is it
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
bull Anchor objectbull Document objectbull Event objectbull Form and Form Input objectbull Frame Frameset and IFrame objectsbull Image objectbull Location objectbull Navigator objectbull Option and Select objectsbull Screen objectbull Table TableHeader TableRow TableData objectsbull Window object
HTML DOM Objects
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Java-based parsers (eg Sun Project X IBM XML4J Apache Xerces)MS IE5 browser COM programming interfaces for CC++ and MS Visual Basic ActiveX object programming interfaces for script languages
94
DOM Implementations
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Object model coversstructure of a documentbehaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documentssemantics of these interfacesrelationships between interfaces and objects
95
Object-based document modelling
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Based on O-O conceptsmethods (to access or change objectrsquos state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLTXPath data model
a parse tree
96
DOM structure model
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
97
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ltinvoicegtltinvoicegt ltinvoicepage form=00 ltinvoicepage form=00 type=estimatedbillgttype=estimatedbillgt ltaddresseegtltaddresseegt ltaddressdatagtltaddressdatagt ltnamegtLeila LaskuprinttiltnamegtltnamegtLeila Laskuprinttiltnamegt ltaddressgtltaddressgt ltstreetaddressgtPyynpolku 1ltstreetaddressgtPyynpolku 1 ltstreetaddressgtltstreetaddressgt ltpostofficegt70460 KUOPIOltpostofficegt70460 KUOPIO ltpostofficegtltpostofficegt ltaddressgtltaddressgt ltaddressdatagtltaddressdatagt ltaddresseegt ltaddresseegt
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
98
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree) with elements attributes and textnode tree) with elements attributes and text
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
The application support and intermediate DOM which existed before the creation of DOM Level 1Example include the DHTML object model or the Netscape intermediate DOMLevel 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process
99
Structure of DOM Level 0
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Two partsI DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
II DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only no access to the contents of a DTD
100
Structure of DOM Level 1
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for say user actions on elements)methods for traversing the document tree and manipulating regions of document (eg selected by the user of an editor)
101
DOM Level 2
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Consists of 6 different specifications
1 DOM Level 3 Core2 DOM Level 3 Load and Save3 DOM Level 3 XPath4 DOM Level 3 Views and Formatting5 DOM Level 3 Requirements and6 DOM Level 3 Validation which further
enhances the DOM
102
DOM Level 3
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
103
Core Interfaces Node amp its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
ldquoldquoExtended Extended interfacesrdquointerfacesrdquo
DocumentDocument
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
104
DOM interfaces DOM interfaces NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form=00type=estimatedbill
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChildrefChild)insertBefore(newChildrefChild)replaceChild(newChildoldChild)replaceChild(newChildoldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
105
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces DOM interfaces DocumentDocument
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
106
DOM interfaces DOM interfaces ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form=00form=00type=estimatedbilltype=estimatedbill
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
to handle ordered lists of nodes NodeList eg from NodechildNodes or ElementgetElementsByTagName(name)
all descendant elements of type name in document order
to access unordered sets of nodes by name NamedNodeMap
eg from NodeattributesNodeLists and NamedNodeMaps are live
changes to the document structure reflected to their contents
107
Additional Core Interfaces
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Each DOM object X lives in the context of a Document XownerDocumentObjects implementing interface Y are created by factory methods
DcreateY(hellip) where D is a Document object Eg createElement(A) createAttribute(href) createTextNode(Hello)
Creation and persistent saving of Documents left to be specified by implementations
108
Object Creation in DOM
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
public static void main(String args[]) if (argslength gt 0)
String fileName = args[0] BuildXml buildXml = new
BuildXml(fileName) else
Systemerrprintln(Give filename as argument)
main
109
The main routine for BuildXml
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
110
HTML Node Hierarchy
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
How Javascript Interact With HTML DOM
111
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page Some simple examples of this usage are
A) Opening or popping up a new window with programmatic control over the size position and look of the new window (ie whether the menus toolbars etc are visible) B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server
C) Changing images as the mouse cursor moves over them This effect is often used to draw the users attention to important links displayed as graphical elements
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Javascript Objects
Object Description Window Represents a browser window A that is created
automatically with every instance of a ltbodygt or ltframesetgt tag
Navigator Contains information about the clients browser
Screen Contains information about the clients display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
112
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
HTML DOM Objects
Object DescriptionAnchor Represents an ltagt element
Document Represents the entire HTML document and can be used to access all elements in a page
Frame frameset Represents a ltframegtltframesetgt element
Image Represents an ltimggt element
Event Represents the state of an event
Form Represents a ltformgt element
Option Select Represent an ltoptiongt element selection list in an HTML document
Table TableHeader TableRow
Represent a lttablegt lttdgt and lttrgt element
113
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
var link = documentcreateElement(a) linksetAttribute(href mypagehtm)
114
Adding in a new element
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
by location documentchildNodes[1]childNodes[0] Find the main document element (HTML) and
find its second child (BODY) then look for its first child (DIV)
by ID documentgetElementById(myDiv)appendChild(txt)
115
locating a slot in the document
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
documentchildNodes[1]childNodes[1]childNodes[0]styledisplay = none
116
Hiding an element
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
ltscript language=JavaScriptgt
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
processing the document goes here
ltscriptgt
117
Loading an XML document object into the parser
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
ltscript language=JavaScriptgt
load up variable var with some xml
var text=ltnotegt
text=text+lttogtJohnlttogtltfromgtRobertltfromgt
text=text+ltheadinggtReminderltheadinggt
text=text+ltbodygtDont forget your homeworkltbodygt
text=text+ltnotegt now create the DO
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocloadXML(text)
process the document
ltscriptgt 118
Manually loading XML into the parser
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
documentwrite(xmlDocparseErrorproperty) errorCode Returns a long integer error code reason Returns a string explaining the reason for the
error line Returns a long integer representing the line
number for the error linePos Returns a long integer representing the line
position for the error srcText Returns a string containing the line that caused
the error url Returns the url pointing the loaded document filePos Returns a long integer file position of the error 119
parseError object
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
set xmlDoc=CreateObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
for each x in xmlDocdocumentElementchildNodes
documentwrite(xnodename)
documentwrite( )
documentwrite(xtext)
next
120
Traversing nodes
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
var xmlDoc = new ActiveXObject(MicrosoftXMLDOM)
xmlDocasync=false
xmlDocload(notexml)
documentwrite(xmlDocgetElementsByTagName(from)item
(0)text)
121
Calling XML nodes by name
Questions
Questions