tags and is used to make websites more dynamic and interactive by responding to user events. It is an interpreted client-side scripting language that is supported by most modern browsers."> tags and is used to make websites more dynamic and interactive by responding to user events. It is an interpreted client-side scripting language that is supported by most modern browsers.">
JSlecture 131848569435884737
JSlecture 131848569435884737
Introduction to JavaScript
Introduction
1
What is JavaScript ?
∗ Client‐side language.( run in the client browser)
∗ 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.
∗ Supported by Netscape 2+, Internet Explorer 3+, Opera 3+ and most of the other
modern web browsers.
What is JavaScript
2
What Can JavaScript Do?
3
When not to use JavaScript
• Variable names are untyped: the type of a variable depends on the value it is currently holding
4
Java VS JavaScript
Java JavaScript
Variable data types must be declared Variable data types not declared (loose
(strong typing). typing).
10
5
Where Do You Place Scripts?
• JavaScript can be put in the <head> or in the <body> of an HTML
document
• JavaScript functions should be defined in the <head>
• This ensures that the function is loaded before it is needed
• JavaScript in the <body> will be executed as the page loads
• JavaScript can be put in a separate .js file
• <script src="myJavaScriptFile.js"></script>
• Put this HTML wherever you would put the actual JavaScript code
• An external .js file lets you use the same JavaScript on multiple
HTML pages
• The external .js file cannot itself contain a <script> tag
• JavaScript can be put in HTML form object, such as a button
• This JavaScript will be executed when the form object is used
Placement Scripts
12
6
Referencing External JavaScript File
What is an Event?
∗ The JavaScript event handler is placed inside an HTML tag like so:
<a href="#" onclick="window.close();">Close this window</a>
14
7
Commonly used event handlers
<html>
<body>
<script type="text/javascript">
document.write("HelloWorld!")
</script>
</body>
</html>
The above code will produce this output on the HTML page.
HelloWorld!!
16
8
∗ To insert a JavaScript into an HTML page, we use the <script> tag.
∗ The <script type="text/javascript"> and </script> 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.
17
∗ The comments around the script are there so that old browsers that
don’t understand the script tag won’t display the code as text on the
page.
∗ If the browser can do JavaScript, then it will ignore the comments.
18
9
<html>
<body>
<script type="text/javascript">
...
</script>
</body>
</html>
19
document.write("Hello World!")
20
10
∗ 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.
<html>
<head>
<script type=“text/javascript”>
……
</script>
</head>
<body>
<script type=“text/javascript”>
……
</script>
</body>
21
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.
22
11
A simple example for external scripts
∗ Save as main.html
<html>
<head>
<body>
<script language="javascript" type="text/javascript"
src="hello.js">
</body>
</head>
</script>
∗ Save as hello.js
23
Output
Hello World!
24
12
<noscript> tag
25
Example
<noscript>
Your browser does not support JavaScript!
</noscript>
26
13
<html>
<head>
<body>
...
...
<script type="text/javascript">
<!‐‐
document.write("Hello World!")
//‐‐>
</script>
<noscript>
Your browser does not support JavaScript!
</noscript>
...
...
</body>
</head>
</html>
27
Primitive Datatypes
14
JavaScript Variable
Comments
15
31
32
16
33
34
17
Practice
∗ Write a program by putting all of the alert statements into the <head> section of the page. This way,
they load up before that page even displays any data
∗ Yourcode would should have the following info:
∗ <script language="JavaScript" type="text/javascript">
<!‐‐
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 can\'t even close your browser window until the demonstration is done.');
alert('Isn\'t this annoying?');
alert('This could potentially go on forever');
alert('Ok, we\'ll stop.');
alert('But first, you have to promise to never do this.');
alert('You have to promise..');
alert('Are you sure your fingers aren\'t crossed?');
alert('Hey! Your toes too!');
alert('OK, we believe you.');
alert('This concludes annoying JavaScript test number 1.');
//‐‐>
</script>
∗ Follow up the above code with another little <body> script with another write() method to give you
a message:
∗ document.write('wasn\'t that annoying?');
35
∗ Scripts that will write out text or HTML code out onto the page must be
placed in its <body> section.
∗ To write out text or HTML to a page, we use the document
object's 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 viewer's 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
don't need thereturn 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
18
Variables
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
19
39
Variable Declarations
40
20
Variables can also have text values.
∗ Here's 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:
∗ document.write("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";
∗ document.write(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
42
21
Observations
∗ Sometimes it can seem a little confusing as to when you should use var, and
when you don't need to. So let's clear this up a bit.
∗ You don't need to use var for the same variable more than once, you only
need it when you first declare that variable. For example, let's 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
already declared the variable at the beginning of your script, you don't need
to use var again.
∗ my_name = "mortimer";
∗ Note: You may notice when looking at some scripts that people don't 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
22
Variables Summary
45
Data Types
46
23
Numeric Data Types
47
Strings
∗ • A string variable can store a sequence of
∗ alphanumeric characters, spaces and special
∗ characters.
∗ • String can also be enclosed in single quotation
∗ marks (‘) or in double quotation marks (“).
∗ • What is the data type of “100”?
∗ – String but not number type
∗ • Pay attention to the special characters.
48
24
Strings example
49
What is an Object?
• An object is a thing, anything, just as things in
the real world.
– E.g. (cars, dogs, money, books, …)
• In the web browser, objects are the browser
window itself, forms, buttons, text boxes, …
• Methods are things that objects can do.
– Cars can move, dogs can bark.
– Window object can alert the user “alert()”.
• All objects have properties.
– Cars have wheels, dogs have fur.
– Browser has a name and version number.
50
25
Object in JavaScript
51
Object in JavaScript
26
Object in JavaScript - properties
•Properties are the values associated with an object.
<script type="text/javascript">
</script>
53
<script type="text/javascript">
var str="Hello world!"
document.write(str.toUpperCase())
</script>
HELLO WORLD!
54
27
The most commonly used JavaScript objects
Object Properties Methods
Window defaultStatus, frames, opener, parent, Alert, blur ,close, confirm, focus, open,
scroll, self, status, top, window prompt, clearTimeout, setTimeout
Frame defaultStatus, frames, opener, parent, Alert, blur, close, confirm, focus, open,
scroll, self, status, top, window prompt, clearTimeout, setTimeout
Documents alinkColor, anchors, applets, ares, Clear, close, open, write, writeln
bgColor, cookie, fgColor, forms, images,
lastModified, linkColor, links, location,
referrer, title, vlinkColor
Image Border, complete, heigth, hspace, None
lowwsrc, vspace, width
55
toLowerCase,toUpperCase
56
28
Built‐in JavaScript Objects
∗ String Object
∗ Date Object
∗ Array Object
∗ Math Object
∗ Boolean Object
57
<script type="text/javascript">
58
29
Built-in JavaScript Objects - Date
∗ The Date object is used to work with dates and times.
∗ Example below shows how to use Date() method to get today’s date:
<script type="text/javascript">
document.write(Date())
</script>
59
<script type="text/javascript">
var minutes = 1000*60
var hours = minutes*60
var days = hours*24
var years = days*365
var d = new Date()
var t = d.getTime()
var y = t/years
60
30
Built-in JavaScript Objects - Array
∗ The Array object is used to store a set of values in a single
variable name.
61
62
31
Functions
63
Functions
32
Built‐In Functions
• Functions provided by the language and you cannot change
them to suit your needs.
• Some of the built‐in functions in JavaScript are shown here:
– eval ‐ eval(expr)
• eval evaluates the expression or statements
– isFinite
• Determines if a number is finite
– isNaN
• Determines whether a value is “Not a Number”
– parseInt
• Converts string literals to integers, no number NaN.
– parseFloat
• Finds a floating‐point value at the beginning of a string.
65
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.
function myFunction(parameters) {
statements contained within the function;
}
66
33
User‐Defined Functions
67
Example
∗ function checkEmail() {
∗ var email_addy = prompt('Please enter your email
address','');
var is_email = email_addy.indexOf('@');
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
34
Calling Functions
69
35
Calling a Function With an Event
Handler
∗ One of the more common ways to call a function is
with an event handler. Such an event handler could
look something like this:
<a href = "#" onclick = "swapImage(); return false;">Click
to see an image change</a>
∗ 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:
∗ <body onload = "loadImages();">
71
Passing Variables
∗ You can pass variables to functions from other areas of the page. This is
done using the function's parameters. Here's how this is done. Let's start
with the event handler:
∗ <a href = "#" onclick="varPassTest('Tom', 'Dick', 'Harry'); return false;">Click to
pass some variables to a function</a>
∗ As you can see, we placed three text strings, separated by commas,
between the parentheses of the function call. Here's 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 don't need to initialize these variables
with the var statement, as the are already automatically initialized when used
this way. )
72
36
Simple function
∗ 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 <body> of the document will
ask you for the number and print out the result. The function is contained in
the <head> section.
∗ Here is the body script:
73
Explanation
∗ 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
function's 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
37
Built-in JavaScript Objects - Math
75
76
38
Built-in JavaScript Objects – Math - methods
77
78
39
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 false:
var 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 true:
var myBoolean=new Boolean(true)
var myBoolean=new Boolean("true")
var myBoolean=new Boolean("false")
var myBoolean=new Boolean("Richard")
79
Objects
∗ JavaScript deals with objects. One good way to think about this is to
compare it to real life objects. Let's 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:
∗ car.wheels.tires
∗ Besides tires, car wheels also have hubcaps (ok, not all cars, but let's assume
so). So these objects can be written out this way:
∗ car.wheels.hubcaps
∗ Going back to the tires, we can take this a step further. The car's tires have
tread. So this can be written out in dot syntax like this:
∗ car.wheels.tires.tread
∗ Therefore, it would obviously be incorrect to write
cars.wheels.hubcaps.tread, as hubcaps don't have tread, but tires do. Get it?
Good.
80
40
OBJECTS
81
82
41
Object
METHODS PROPERTIES
Fly () name
Eat()
age
Drink()
EyeColor
A bird (object)
83
1. Direct Instance
84
42
2. Create Template to the object
function Bird(name,age,eyecolor)
{ this.name=name
this.age=age
this.eyecolor=eyecolor
}
When you have template, then you can create new instance of the object :
85
∗ You can also add some methods to the bird object. This is also done inside the template:
function Bird(name,age,eyecolor)
{ this.name=name
this.age=age this.
eyecolor=eyecolor
That methods are just functions attached to objects. Then we will have to write the habitat()
function:
function habitat(new_habitat)
{
this.habitat=new_habitat
}
Eg :
myBird.habitat(“Pond”)
86
43
Cookies
∗ Cookies are variables that can be stored on a user's 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 and whether I look in the lingerie section,
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 document.cookie object is a string representation of all cookies
available to the current web page.
∗ Thedocument.cookie 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
44
Creating / modifying and deleting
cookies
∗ Cookies are created or modified by assigning a name=value pair
to the document.cookie object:
document.cookie = cookieString;
89
Cookies
∗ cookieName and cookieValueThese are strings, and must be URL encoded. They and
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.expiresThis must be written in
full.
∗ The Date.toGMTString() method can return dates in the correct format for you. For
example:var theDate = new Date(); var oneYearLater = new Date( theDate.getTime() +
31536000000 ); var expiryDate = oneYearLater.toGMTString();
∗ 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
45
DOM: What is it?
91
DOM Specification:
92
46
HTML DOM Objects
• Anchor object
• Document object
• Event object
• Form and Form Input object
• Frame, Frameset, and IFrame objects
• Image object
• Location object
• Navigator object
• Option and Select objects
• Screen object
• Table, TableHeader, TableRow, TableData objects
• Window object
DOM: Implementations
Java‐based parsers
(e.g. Sun Project X, IBM XML4J, Apache Xerces)
MS IE5 browser: COM programming interfaces for C/C++ and
MS Visual Basic, ActiveX object programming interfaces for
script languages
94
47
Object‐based document modelling
95
96
48
<invoice>
<invoicepage form="00" XML DOM structure model
type="estimatedbill">
<addressee>
<addressdata>
<name>Leila Laskuprintti</name>
<address>
<streetaddress>Pyynpolku 1 invoice
</streetaddress>
<postoffice>70460 KUOPIO form="00"
invoicepage type="estimatedbill"
</postoffice>
</address>
</addressdata> addressee
</addressee> ...
addressdata
Document
name address
Element
98
49
Structure of DOM Level 0
99
100
50
DOM Level 2
101
DOM Level 3
102
51
Core Interfaces: Node & its variants
Node
CharacterData
EntityReference ProcessingInstruction
103
Node
getNodeType
getNodeValue DOM interfaces: Node
getOwnerDocument
getParentNode
hasChildNodes getChildNodes
getFirstChild
getLastChild invoice
getPreviousSibling
getNextSibling form="00"
hasAttributes getAttributes invoicepage type="estimatedbill"
appendChild(newChild)
insertBefore(newChild,refChild)
addressee
replaceChild(newChild,oldChild)
removeChild(oldChild)
addressdata
Document
name address
Element
Leila Laskuprintti streetaddress postoffice
Text
NamedNodeMap
104 Pyynpolku 1 70460 KUOPIO
52
Node
DOM interfaces: Document
Document
getDocumentElement
createAttribute(name)
createElement(tagName) invoice
createTextNode(data)
getDocType() form="00"
getElementById(IdVal) invoicepage type="estimatedbill"
addressee
addressdata
Document
name address
Element
Leila Laskuprintti streetaddress postoffice
Text
NamedNodeMap
105 Pyynpolku 1 70460 KUOPIO
Node
DOM interfaces: Element
Element
getTagName
getAttributeNode(name)
setAttributeNode(attr) invoice
removeAttribute(name)
getElementsByTagName(name) form="00"
hasAttribute(name) invoicepage type="estimatedbill"
addressee
addressdata
Document
name address
Element
Leila Laskuprintti streetaddress postoffice
Text
NamedNodeMap
106 Pyynpolku 1 70460 KUOPIO
53
Additional Core Interfaces
107
108
54
The main routine for BuildXml
109
110
55
How Javascript Interact With HTML
DOM
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:
111
Javascript Objects
Object Description
Window Represents a browser window. A that is created
automatically with every instance of a <body> or
<frameset> tag
Navigator Contains information about the client's browser
112
56
HTML DOM Objects
Object Description
Anchor Represents an <a> element
∗ var link =
document.createElement('a');
link.setAttribute('href',
'mypage.htm');
114
57
locating a slot in the document
∗ by location:
∗ document.childNodes[1].childNodes[0]
∗ Find the main document element (HTML), and find its
second child (BODY), then look for its first child (DIV)
∗ by ID:
∗ document.getElementById('myDiv').append
Child(txt);
115
Hiding an element
∗ document.childNodes[1].childNodes[1].childNodes[
0].style.display = "none";
116
58
Loading an XML document object into
the parser
∗ <script language="JavaScript">
</script>
117
59
parseError object
∗ document.write(xmlDoc.parseError.property)
∗ 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
Traversing nodes
set xmlDoc=CreateObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.load("note.xml")
120
60
Calling XML nodes by name
document.write(xmlDoc.getElementsByTagName("from").item
(0).text)
121
Questions
61