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.">
[go: up one dir, main page]

0% found this document useful (0 votes)
23 views61 pages

JSlecture 131848569435884737

The document provides an introduction to JavaScript, discussing what it is, how it is used in web pages, and common events and uses. JavaScript can be inserted into HTML pages using <script> 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.

Uploaded by

jabetbackup
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views61 pages

JSlecture 131848569435884737

The document provides an introduction to JavaScript, discussing what it is, how it is used in web pages, and common events and uses. JavaScript can be inserted into HTML pages using <script> 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.

Uploaded by

jabetbackup
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

Web Programming

Introduction to JavaScript

Introduction

• The growth of the WWW has resulted in a demand for dynamic


and interactive websites.

• There are many different kinds of scripting languages –


JavaScript, …

• This lecture aims at offering in‐depth knowledge of JavaScript,


discussing the complexity of scripting and studying various
common examples.

1
What is JavaScript ?
∗ Client‐side language.( run in the client browser)

∗ Scripting language. (interpreted in run‐time)

∗ Not compile like other language (C#, C++, VB.Net 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, array,object,operators and function.

What is JavaScript

• JavaScript was originally developed by Brendan Eich of Netscape under the


name Mocha, which was later renamed to LiveScript, and finally to JavaScript

• A lightweight programming language that runs in a Web browser

• JavaScript is a Client Side Scripting Language.

• Also known as ECMAScript

• Interpreted, not compiled.

• JavaScript Syntax are similar to C and Java Language.

• JavaScript code is usually embedded directly into HTML pages

• JavaScript is reasonably platform‐independent

2
What Can JavaScript Do?

• JavaScript gives HTML designers a programming tool

• JavaScript can put dynamic text into an HTML page

• JavaScript can react to events

• JavaScript can read and write HTML elements

• JavaScript can be used to validate input data

• JavaScript can be used to detect the visitor's browser

• JavaScript can be used to create cookies

More usage of JavaScript

∗ 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 the user enter name whenever the page load
for 1st time. User can used entered value for welcome page.

3
When not to use JavaScript

• When you need to access other resources.


• Files Programs
• Databases
• When you are using sensitive or copyrighted data or algorithms.
• Your JavaScript code is open to the public.

JavaScript is not Java


•Java and JavaScript are two completely different languages in both concept and design!

•JavaScript has some features that resemble features in Java:

• JavaScript has Objects and primitive data types

• JavaScript has qualified names; for example, document.write("Hello World");

• JavaScript has Events and event handlers

• Exception handling in JavaScript is almost the same as in Java

•JavaScript has some features unlike anything in Java:

• Variable names are untyped: the type of a variable depends on the value it is currently holding

• Objects and arrays are defined in quite a different way

• JavaScript is an interpreted language but java is both interpreted and compiled

4
Java VS JavaScript
Java JavaScript

Sun Microsystems Netscape


Much larger and advanced set of Much smaller and simpler set of
commands. commands .

Applets distinct from HTML Code integrated with, and embedded


(accessed from HTML pages). in, HTML.

Variable data types must be declared Variable data types not declared (loose
(strong typing). typing).

Compiled on server before execution Interpreted (not compiled) by client.


on client.

How to Put a JavaScript Into an HTML Page

∗ 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 <script> tag

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

Scripts can be in the either <head> section or


<body> section
• Convention is to place it in the <head> section
<html>
<head>
<script type="text/javascript">
....
</script>
</head>

12

6
Referencing External JavaScript File

• Scripts can be provided locally or remotely accessible


JavaScript file using src attribute
<html>
<head>
<script language="JavaScript“ type="text/javascript“
src="http://somesite/myOwnJavaScript.js">
</script>
<script language="JavaScript“ type="text/javascript“
src="myOwnSubdirectory/myOwn2ndJavaScript.js">
</script>

What is an Event?

∗ Besides being an object oriented programming language, JavaScript is also


an event‐driven language. Let's take a look at what an event is.
∗ Whenever the user does something on a Web page, whether it's loading the
page, clicking on something, or moving the mouse over something, it's
called an event.
∗ For JavaScript to recognize an event, we need and 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 (let's say an 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:
<a href="#" onclick="window.close();">Close this window</a>

14

7
Commonly used event handlers

∗ onclick ‐ Triggered with the object is clicked.


∗ onmouseover ‐ Triggered when the mouse is move over the object.
∗ onmouseout ‐ Triggered when the curser is move off of the object.
∗ onblur ‐ Triggered when the object is no longer selected (like a from 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.
15

<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

∗ The word document.write is a standard JavaScript command for


writing output to a page.
∗ If we had not entered the <script> tag, the browser would have
treated the document.write("Hello World!") command as pure text,
and just write the entire line on the page.
∗ This will be the output

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

var hello = 'Hello World';


document.write(hello);

23

Output

Hello World!

24

12
<noscript> 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 <script> tag, but
does not support the script in it.
∗ If a browser supports scripting, it will not display the text in the
noscript element.

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

• JavaScript has three “primitive” types: number, string, and


boolean
• Numbers are always stored as floating‐point values
• Hexadecimal numbers begin with 0x
• Some platforms treat 0123 as octal, others treat it as decimal
• Strings may be enclosed in single quotes or double quotes
• Strings can contains \n (newline), \" (double quote), etc.
• Booleans are either true or false
• 0, "0", empty strings, undefined, null, and NaN are false , other
values are true

14
JavaScript Variable

• You create a variable with or without the “var” statement


∗ var num = “1”;
∗ var name = “Kaushal”;
∗ var phone = “123‐456‐7890”;
• Variables names must begin with a letter or underscore
• Variable names are case‐sensitive
• Variables are untyped (they can hold values of any type)
• The word var is optional (but it’s good style to use it)
• Variables declared within a function are local to that
function (accessible only within that function)
• Variables declared outside a function are global (accessible
from anywhere on the page)

Comments

• Comments are as in C or Java:


• Single Line Comment //
• Paragraph Comment /*….*/
• Java’s javadoc comments, /** ... */, are treated just the
same as /* ... */ comments; they have no special
meaning in JavaScript

15
31

32

16
33

JavaScript Popup Boxes


• Alert box
> User will have to click "OK" to proceed
> alert("sometext")
• Confirm box
> User will have to click either "OK" or "Cancel" to proceed
> confirm("sometext")
• Prompt box
> User will have to click either "OK" or "Cancel" to proceed
after
entering an input value
> prompt("sometext","defaultvalue")

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

Your First Scripts Summary

∗ 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

• JavaScript allows you to declare and use variables to


store values.
• How to assign a name to a variable?
– Include uppercase and lowercase letters
– Digits from 0 through 9
– The underscore _ and the dollar sign $
– No space and punctuation characters
– First character must be alphabetic letter or underscore
99Total?, 012345number?, …
– Case‐sensitive
– 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

19
39

Variable Declarations

∗ 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
don't 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

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

∗ 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 don't 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, don't
enclose it in quotes.
43

To var or not to var

∗ 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

∗ 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

Data Types

JavaScript allows the same variable to contain different types


of data values.
• Primitive data types
– Number: integer & floating‐point numbers
– Boolean: logical values “true” or “false”
– String: a sequence of alphanumeric characters
• Composite data types (or Complex data types)
– Object: a named collection of data
– Array: a sequence of values
• Special data types
– Null: an initial value is assigned
– Undefined: the variable has been created by not yet assigned a value

46

23
Numeric Data Types

• It is an important part of any programming


language for doing arithmetic calculations.
• JavaScript supports:
– Integers: A positive or negative number with no
decimal places.
• Ranged from –253 to 253
– Floating‐point numbers: usually written in
exponential notation.
• 3.1415…, 2.0e11

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

∗ 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

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.
52

26
Object in JavaScript - properties
•Properties are the values associated with an object.

•Below examples shows how to access length property of


document object to return the number of characters in a string.

<script type="text/javascript">

var txt="Hello World!“


document.write(txt.length)

</script>

•The output of the code above will be:


12 ( H e l l o [space] W o r l d ! )

53

Object in JavaScript - methods

•Methods are the actions that can be performed on objects.

•In the following example we are using the toUpperCase() method


of the String object to display a text in uppercase letters:

<script type="text/javascript">
var str="Hello world!"
document.write(str.toUpperCase())
</script>

•The output of the code above will be:

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

Location Hash, host, hostname, href, pathname, Reload, replace


por, protocol, search

History Length, forward, go Back

Navigator appCodeName, appName, appVersion, javaEnabled


mimeTypes, plugins, userAgents

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

Form Action, elements, encoding, FileUpload, Submit, reset


method, name, target

Text defaultValue, name, type, value Focus, blur, select

55

The most commonly used Built‐in 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,

toLowerCase,toUpperCase

56

28
Built‐in JavaScript Objects

∗ String Object
∗ Date Object
∗ Array Object
∗ Math Object
∗ Boolean Object

57

Built-in JavaScript Objects - String


∗ 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:

<script type="text/javascript">

var txt="Hello World!”


document.write(txt.length)
</script>

∗ The above code will result in following output:


12

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>

∗ The output will be:


Mon June 09 15:51:51 2012

59

Built-in JavaScript Objects - Date


∗ This 2nd example shows how to use getTime() method to calculate
years since 1970:

<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

document.write("It's been: " + y + " years since 1970/01/01!")


</script>
∗ The output will be:
It's been: 37.86941401639396 years since 1970/01/01!

60

30
Built-in JavaScript Objects - Array
∗ 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,


myArray:
var mycars=new Array()
mycars[0]=“Lotus"
mycars[1]="Volvo"
mycars[2]="BMW"
OR
var mycars=new Array("Saab","Volvo","BMW")

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:
document.write(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]=“Lexus”
document.write(mycars[0])
will result in the following output:
Lexus

62

31
Functions

∗ 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 don't. As you will see in this lecture,
functions are a great thing to know how to use.

63

Functions

• A function is a block of organized reusable


code (a set of statements) for performing a
single or related action.
• Begins with keyword “function” and the
function name and “( …)”
• Inside the parentheses
– We can pass parameters to the function
– E.g. function myfuc(arg1, arg2) {…}
– Built‐in and user‐defined functions
64

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.

∗ 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

33
User‐Defined Functions

• For some functionality, you cannot achieve by


only using the built‐in functions.
• You can define a function as follows
function <function_name> (parameters)
{
// code segments;
}

67

Example

∗ Here is an example of a scripts 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_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

∗ 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 a Function From a Script

∗ A function is called within a script by writing its name,


followed by parentheses, with or without parameters.
Let’s look at functions without parameters, for simplicity's
sake.
∗ alert('we need to check to see where the @ symbol is at');
∗ //Call the function
checkEmail();
∗ If we are assuming this is a separate script from the one
above (and we are), then we don't 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

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:

// Prompt the user for a number.


var initial_number = prompt('Please type in a number','');
// Call the function, and pass it initial_number for processing.
fixed_number = addDollar(initial_number);
// take the number the function returned and write it out.
document.write('This is your number converted to a dollar amount: ' + fixed_number);
Here is the function in the <head> script.
function 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

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

∗ 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 - values

∗ 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 1/2, 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:
Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E

76

38
Built-in JavaScript Objects – Math - methods

∗ 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:
document.write(Math.round(4.7))
∗ The code above will result in the following output:
5

77

Built-in JavaScript Objects - Boolean

∗ 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

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

∗ 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:
∗ car.wheels.hubcaps.colour.grey
∗ If we wanted to change the colour of our car's hubcaps, we could
do so by writing:
∗ car.wheels.hubcaps.colour.silver
∗ Ok, we can't 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 car's properties (wheels,
hubcaps, etc) are also objects in their own right, which can have
their own properties.

81

How to create an object?

1. Create a direct instance of an object


2. Create template of an object

82

41
Object

METHODS PROPERTIES

Fly () name

Eat()
age

Drink()
EyeColor

A bird (object)

83

1. Direct Instance

Add few properties to the bird


BirdObj=new Object()
BirdObj.name=“MorningBird“
BirdObj.age=2
BirdObj.eyecolor=“green"

Add methods to the bird


BirdObj.fly = fly
BirdObj.eat = eat
BirfObj.Breath = breath

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 :

myBird= new Bird (“Parrot”, 2, “blue”)

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

this.habitat = habitat  new method


}

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;

∗ 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=value;etc. and
assigned as a single string to document.cookie. Only the cookie
name and value are required, all other values are optional.

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?

∗ 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:

“a platform‐ and language‐neutral interface that


allows programs and scripts to dynamically access
and update the content, structure and style of
documents. … [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 them.”

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

Object model covers


structure of a document
behaviour of a document and its constituent objects
DOM defines
interfaces and objects for representing and
manipulating documents
semantics of these interfaces
relationships between interfaces and objects

95

DOM structure model


Based on O-O concepts:
methods (to access or change object’s state)
interfaces (declaration of a set of methods)
objects (encapsulation of data and methods)
Roughly similar to the XSLT/XPath data model
≈ a parse tree

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

Text Leila Laskuprintti streetaddress postoffice


97
NamedNodeMap
Pyynpolku 1 70460 KUOPIO

HTML DOM structure model


The DOM presents an HTML document as a tree-tree-structure (a node
tree), with elements, attributes, and text.

98

49
Structure of DOM Level 0

The application support and intermediate DOM


which existed before the creation of DOM Level 1.
Example include the DHTML object model or the
Netscape intermediate DOM.
Level 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 1


Two parts:
I: 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 documents
Level 1 intentionally limited to representation and manipulation of
document structure and content
document instance only; no access to the contents of a DTD

100

50
DOM Level 2

support for namespaces


accessing elements by ID attribute values
optional features
interfaces to document views and stylesheets
an event model (for, say, user actions on elements)
methods for traversing the document tree and manipulating
regions of document (e.g., selected by the user of an editor)

101

DOM Level 3

Consists of 6 different specifications:

1. DOM Level 3 Core;


2. DOM Level 3 Load and Save
3. DOM Level 3 XPath;
4. DOM Level 3 Views and Formatting;
5. DOM Level 3 Requirements; and
6. DOM Level 3 Validation, which further enhances
the DOM

102

51
Core Interfaces: Node & its variants

Node

Document DocumentFragment Element Attr

CharacterData

Comment Text CDATASection “Extended


interfaces”

DocumentType Notation Entity

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

to handle ordered lists of nodes: NodeList


e.g. from Node.childNodes or
Element.getElementsByTagName("name")
all descendant elements of type "name" in document order
to access unordered sets of nodes by name:
NamedNodeMap
e.g. from Node.attributes
NodeLists and NamedNodeMaps are "live":
changes to the document structure reflected to their
contents

107

Object Creation in DOM


Each DOM object X lives in the context of a Document:
X.ownerDocument
Objects implementing interface Y are created by factory
methods
D.createY(…) ,
where D is a Document object. E.g:
createElement("A"),
createAttribute("href"),
createTextNode("Hello!")
Creation and persistent saving of Documents left to be
specified by implementations

108

54
The main routine for BuildXml

public static void main(String args[]){ if


(args.length > 0) {
String fileName = args[0];
BuildXml buildXml = new
BuildXml(fileName);
} else {
System.err.println(
"Give filename as argument");
};
} // main

109

HTML Node Hierarchy

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:

A) Opening or popping up a new window with programmatic control


over the size, position and 'look' of the new window
(i.e. 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 user's attention to important
links displayed as graphical elements.

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

Screen Contains information about the client's display screen

Location Contains information about the current URL

History Contains the visited URLs in the browser window

112

56
HTML DOM Objects
Object Description
Anchor Represents an <a> element

Document Represents the entire HTML document and can be used to


access all elements in a page.
Frame/ frameset Represents a <frame>/<frameset> element

Image Represents an <img> element

Event Represents the state of an event

Form Represents a <form> element

Option / Select Represent an <option> element / selection list in an HTML


document.
Table, TableHeader, Represent a <table>, <td> and <tr> element.
TableRow 113

Adding in a new 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">

var xmlDoc = new ActiveXObject("Microsoft.XMLDOM")


xmlDoc.async="false"
xmlDoc.load("note.xml")

// ....... processing the document goes here

</script>

117

Manually loading XML into the parser


∗ <script language="JavaScript">
// load up variable var with some xml
var text="<note>"
text=text+"<to>John</to><from>Robert</from>"
text=text+"<heading>Reminder</heading>"
text=text+"<body>Don't forget your homework!</body>"
text=text+"</note>" // now create the DO

var xmlDoc = new ActiveXObject("Microsoft.XMLDOM")


xmlDoc.async="false"
xmlDoc.loadXML
loadXML(text)
loadXML
// ....... process the document
</script> 118

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")

for each x in xmlDoc.documentElement.childNodes


document.write(x.nodename)
document.write(": ")
document.write(x.text)
next

120

60
Calling XML nodes by name

var xmlDoc = new ActiveXObject("Microsoft.XMLDOM")


xmlDoc.async="false"
xmlDoc.load("note.xml")

document.write(xmlDoc.getElementsByTagName("from").item
(0).text)

121

Questions

61

You might also like