[Go to site: main page, start]

0% found this document useful (0 votes)
4 views40 pages

Chapter 3 JavaScript

JavaScript is an object-oriented scripting language primarily used for creating interactive web pages and is embedded within HTML documents. It allows for client-side programming, enabling dynamic features like form validation and event handling, while being platform-independent. JavaScript differs from Java in that it is interpreted directly in the browser and is simpler, making it suitable for web development tasks.

Uploaded by

Habtamu Asayto
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)
4 views40 pages

Chapter 3 JavaScript

JavaScript is an object-oriented scripting language primarily used for creating interactive web pages and is embedded within HTML documents. It allows for client-side programming, enabling dynamic features like form validation and event handling, while being platform-independent. JavaScript differs from Java in that it is interpreted directly in the browser and is simpler, making it suitable for web development tasks.

Uploaded by

Habtamu Asayto
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

11/16/2017

JAVASCRIPT
• What is JavaScript?
– JavaScript: the first Web scripting language,
Client side programming developed by Netscape in 1995 syntactic
similarities to Java/C++,
• but simpler & more flexible
• (loose typing, dynamic variables, simple objects)
JavaScript – An object-oriented scripting language that is
designed primarily for people who are building web
pages using HTML.

Client-side programming Client-side programming cont…


– Javascript programs are embedded within HTML • client-side programming:
documents in source code form. – programs are written in a separate programming
– The script is interpreted by the browser. language
• Platform independence. e.g., JavaScript, VBScript
• Recall: HTML is good for developing static pages – programs are embedded in the HTML of a Web page,
– can specify text/image layout, presentation, links,... with tags to identify the program component
– Web page looks the same each time it is accessed e.g., <script type="text/javascript"> … </script>
– in order to develop interactive/reactive pages, must – the browser executes the program as it loads the
integrate programming page, integrating the dynamic output of the program
with the static content of HTML

3 4

1
11/16/2017

Common scripting tasks


Javascript code added to HTML can perform a wide variety of
limitations of client-side scripting
functions:
◦ Decision making. • since script code is embedded in the page, viewable to the
◦ Submitting forms. world
◦ Performing complex mathematical calculations. • for security reasons, scripts are limited in what they can do
◦ Data entry validation, etc e.g., can't access the client's hard drive
◦ adding dynamic features to Web pages • since designed to run on any machine platform, scripts do not
 image rollovers
contain platform specific commands
 time-sensitive or random page elements • script languages are not full-featured
 handling cookies – e.g., JavaScript objects are crude, not good for large
 defining programs with Web interfaces project development
◦ utilize buttons, text boxes, clickable images, prompts, frames

5 6

Introduction to JavaScript
• Javascript is object-oriented. • When to use JavaScript?
– Data entry validation
– It allows interaction with the properties of • If form fields need to be filled out for processing on the
objects that it recognizes. server, I let clientside scripts prequalify the data
entered by the user.
• Internal built-in objects (e.g. window object).
– Dynamic HTML interactivity.
• Browser objects (e.g. document object).
• if you intend to make the content dance on the page,
scripting makes that happen.
– CGI prototyping
• Sometimes you want a CGI program to be at the root of
your application because it reduces the potential
incompatibilities among browser brands and versions.
• Use this opportunity to polish the user interface before
implementing the application as a CGI.
7

2
11/16/2017

Introduction to JavaScript Javascript and Java


• When to use JavaScript? • Although the names resemble quite closely,
– Creating web pages that “think.” they are different languages.
• you may develop new, intriguing ways to make your • Some facts:
pages appear smart
– Both are object-oriented languages.
– Offloading a busy server. – Javascript programs are interpreted in source code
• If you have a highly trafficked web site, it may form.
be beneficial to convert frequently used CGI – Java programs are first compiled into a device
processes to client-side JavaScript scripts independent byte code format, which is then
interpreted.
10

• Javascript is a small language and does not  JavaScript code can be embedded in a Web page using SCRIPT tags
◦ the output of JavaScript code is displayed as if directly entered in
have many features that exist in Java. HTML
• Java is a powerful language and can be used in  [Link] displays text in page text to be displayed can
include HTML tags
extremely sophisticated applications.  the tags are interpreted by the browser when the text is displayed
 as in C++/Java, statements end with ; but it Optional
 JavaScript comments similar to C++/Java
◦ // starts a single line comment
◦ /*…*/ enclose multi-line comments

11 12

3
11/16/2017

Example JavaScript data types & variables


<html> Hello world!
<head> How are • JavaScript has three primitive data types
<title>JavaScript Page</title> you?
</head> Here is some static text as well.
• strings : "foo" 'howdy do' "I said 'hi'." ""
<body> • numbers : 12 3.14159 1.5E6
<script type="text/javascript">
// silly code to demonstrate output
• booleans : true false
[Link]("Hello world!");
[Link]("<p>How are <br />" +
"<i>you</i>?</p>");
</script>
<p>Here is some static text as well.
</p>
</body>
</html>

13 14

assignments are as in C++/Java


Example
• message = "howdy";
<html> • pi = 3.14159;
<head> <title>Data Types and Variables</title></head> • variable names are sequences of letters,
<body> digits, and underscores: start with a letter
<script type="text/javascript">
x = 1024; • variables names are case-sensitive
[Link]("<p>x = " + x + "</p>");
• you don't have to declare variables, will
x = "foobar";
[Link]("<p>x = " + x + "</p>"); be created the first time used
</script> • variables are loosely typed, can assign
</body>
different types of values
</html>

15 16

4
11/16/2017

JavaScript operators & control statements


<html>
<head><title>Folding Puzzle</title></head>
<body> • standard C++/Java operators & control
<script type="text/javascript">
distanceToSun = 93.3e6*5280*12; statements are provided in JavaScript
thickness = .002;
foldCount = 0;
• +, -, *, /, %, ++, --, …
while (thickness < distanceToSun) { • ==, !=, <, >, <=, >=
thickness *= 2;
foldCount++; • &&, ||, !
}
[Link]("Number of folds = " + foldCount); • if, if-else, while, do, …
</script>
</body>
</html>

17 18

JavaScript Terminology. Objects


• JavaScript programming uses specialized • Objects refers to windows, documents,
terminology. images, tables, forms, buttons or links, etc.
• Understanding JavaScript terms is • Objects should be named.
fundamental to understanding the script. • Objects have properties that act as modifiers.
– Objects, Properties, Methods, Events, Functions,
Values, Variables, Expressions, Operators.

19 20

5
11/16/2017

Properties Methods
• Properties are object attributes. • Methods are actions applied to particular
objects.
• Object properties are defined by using the
object's name, a period, and the property • Methods are what objects can do.
name. – e.g., [Link](”Hello
World")
– e.g., background color is expressed by:
• document is the object.
[Link] .
• write is the method.
– document is the object.
– bgcolor is the property.

21 22

[Link](“String”) [Link](“String”)
<HTML>
<HEAD><TITLE>Hello!</TITLE></HEAD>
<BODY>
<H1> First JavaScript Page </H1>
<SCRIPT TYPE="text/javascript">
/* --->
----- */
[Link]("<HR/>");
[Link]("Hello WWW!");
[Link]("<HR/>");
//-->
</SCRIPT>
</BODY>
</HTML>
23 24

6
11/16/2017

Events…
Events • JavaScript is event-driven.
– Something has to happen before the JavaScript is
• Events associate an object with an action. executed.
• JavaScript defines various events:
– e.g., the OnMouseover event handler action can
– onClick – link or image is clicked
change an image.
– onSubmit – a form is submitted
– e.g., the onSubmit event handler sends a form. – onMouseOver – the mouse cursor moves over it
• User actions trigger events. – onChange – a form control is changed
– onLoad – something gets loaded in the browser
– etc.
– Events are specified in the HTML code.

25 26

Event example
<html> Functions
<head>
<script language=“javascript”> • Functions are named statements that
function funct() {
performs tasks.
// code
} – e.g., function doWhatever ()
</script> {statement here}
</head> – The curly braces contain the statements of the
<body> function.
<img src=“[Link]” > </body>
• JavaScript has built-in functions, and you can
</html> write your own.
NB: Language=“JavaScript” is optional.

27 28

7
11/16/2017

Values Variables
• Values are bits of information. • Variables contain values and use the equal
• Values types and some examples include: sign to specify their value.
– Number: 1, 2, 3, etc. • Variables are created by declaration using the
– String: characters enclosed in quotes. var command with or without an initial value
– Boolean: true or false. state.
– Object: image, form – e.g. var month;
– Function: validate, doWhatever – e.g. var month = April;
– e.g. month = April;

29 30

Expressions Methods of Using JavaScript.


• Expressions are commands that assign values 1. JavaScripts can reside in a separate page.
to variables. 2. JavaScript can be embedded in HTML
• Expressions always use an assignment documents -- in the <head>, in the <body>,
operator, such as the equals sign. or in both.
– e.g., var month = May; is an expression. 3. JavaScript object attributes can be placed in
• Expressions end with a semicolon. HTML element tags.
e.g., <body >

31 32

8
11/16/2017

1. Using Separate JavaScript Files.


• Linking can be advantageous if many pages
use the same script.
• Use the source element to link to the script
file.
<script src="[Link]”
language="JavaScript1.2”
type="text/javascript">
</script>

33 34

2. Embedding JavaScript in HTML. Javascript Examples


• Simple message output in varying sizes.
• When specifying a script only the tags <HTML>
<TITLE> Displaying Text </TITLE>
<script> and </script> are essential, <BODY>
but complete specification is recommended: <SCRIPT>
[Link] ("<H1>Hello Good Day</H1>");
<script language="javascript”
[Link] ("<H3>Best of Luck.</H3>");
type="text/javascript">
</SCRIPT>
/*-- Begin hiding
</BODY>
---*/
</HTML>
[Link]=”[Link]" Hello Good Day
Best of Luck.
// End hiding script-->
</script>
35 36

9
11/16/2017

Alert Box

• An alert box is often used if you want to make sure


information comes through to the user.
Example :
• When an alert box pops up, the user will have to click "OK" to
proceed. <body Enjoy your visit.
Your feedback can improve cyberspace. Please
• The following script in the <body> tag uses the onLoad let me know if you detect any problems.
event to display an Alert window Thank you.')">
• The message is specified within parenthesis.

Syntax
• alert("sometext");

37 38

Prompt Box
Example
<html> • A prompt box is often used if you want the user
<head>
<script type="text/javascript"> to input a value before entering a page.
function show_alert()
{
• When a prompt box pops up, the user will have
alert("I am an alert box!"); to click either "OK" or "Cancel" to proceed after
} entering an input value.
</script>
</head> • If the user clicks "OK" the box returns the input
<body> value. If the user clicks "Cancel" the box returns
<input type="button" value="Show alert null.
box" /> • Syntax
</body> • prompt("sometext","defaultvalue");
</html>

39 40

10
11/16/2017

Example 1 Example 2
<html> <html>
<head> <head>
<script type="text/javascript">
function show_prompt() <title>Interactive page</title>
{ </head>
var name=prompt("Please enter your name",“Abebe Tesema ");
if (name!=null && name!="") <body>
{ <script type="text/javascript">
[Link]("Hello " + name + "! How are you today?"); userName = prompt("What is your name?", "");
} userAge = prompt("Your age?", "");
} userAge = parseFloat(userAge);
</script> [Link]("Hello " + userName + ".")
</head>
<body> if (userAge < 18) {
[Link](" Do your parents know " + "you are online?");
}
<input type="button" value="Show
prompt box" /> </script>
<p>The rest of the page...
</body> </body>
</html> </html>
41 42

Javascript Confirm Box


• crude user interaction can take place using prompt • A Javascript confirmation box is a handy way to give the visitor a choice of
whether or not an action is to be performed.
• 1st argument: the prompt message that appears in the dialog
• When a confirm box pops up, the user will have to click either "OK" or
box "Cancel" to proceed.
• 2nd argument: a default value that will appear in the box (in • If the user clicks "OK", the box returns true. If the user clicks "Cancel", the
case the user enters nothing) box returns false.
• the function returns the value entered by the user in the • Syntax
dialog box (a string) confirm (“The question to ask …”);

• if value is a number, must use parseFloat to convert

43 44

11
11/16/2017

Example
Example <html>
<head>
<script type="text/javascript">
function show_confirm()
• Simple event handler with a confirm box. {
var r=confirm("Press a button");
if (r==true)
<SCRIPT> {
alert("You pressed OK!");
function respond() }
else
{ {
confirm (“Hello there!”); alert("You pressed Cancel!");
}
} }
</script>
</SCRIPT> </head>
<body>
<H2>Click on the following button</H2>
<FORM> <input type="button" value="Show confirm box" />

<INPUT TYPE="button" VALUE="Click and See" </body>


</html>
>
</FORM>
45 46

The Math Object & Math Methods


• Another way of performing a calculation is to use
the JavaScript built-in Math methods.
• These methods are applied to an object called the
Math object.
• The syntax for applying a Math method is:
value = [Link](variable);
• For example,
AbsValue = [Link](NumVar);

47 48

12
11/16/2017

 the Math object contains functions and


constants
Method Description – exp(x) Returns the value of Ex
 abs(x) Returns the absolute value of x – floor(x) Returns x, rounded downwards to the nearest
integer
 acos(x) Returns the arccosine of x, in radians
– log(x) Returns the natural logarithm (base E) of x
 asin(x) Returns the arcsine of x, in radians – max(x,y,z,...,n) Returns the number with the highest value
 atan(x) Returns the arctangent of x as a – min(x,y,z,...,n) Returns the number with the lowest value
numeric value between -PI/2 and PI/2 radians – pow(x,y) Returns the value of x to the power of y
 atan2(y,x) Returns the arctangent of the – random() Returns a random number between 0 and 1
quotient of its arguments – round(x) Rounds x to the nearest integer
 ceil(x) Returns x, rounded upwards to the – sin(x) Returns the sine of x (x is in radians)
nearest integer – sqrt(x) Returns the square root of x
 cos(x) Returns the cosine of x (x is in – tan(x) Returns the tangent of an angle
radians)

49 50

Creating JavaScript Functions Creating JavaScript Functions….

function function_name(parameters) { • Function names are case-sensitive.


JavaScript commands • The function name must begin with a letter or underscore ( _ )
and cannot contain any spaces.
}
• There is no limit to the number of function parameters that a
function may contain.
– parameters are the values sent to the function (note: not
all functions require parameters) • The parameters must be placed within parentheses, following
the function name, and the parameters must be separated by
– { and } are used to mark the beginning and end of the commas.
commands in the function.

51 52

13
11/16/2017

Performing an Action with a Function Performing an Action with a Function

The following function displays a message with the current date: To call the ShowDate function, enter:
function ShowDate(date) { var Today = “3/9/2010”;
[Link](“Today is” + date + “<br>”); ShowDate(Today);
} – the first command creates a variable named “Today” and
assigns it the text string, “3/9/2010”
– there is one line in the function’s command block, which
displays the current date along with a text string – the second command runs the ShowDate function, using the
value of the Today variable as a parameter
– result is “Today is 3/9/2010”

53 54

Placing a Function in an HTML File


Returning a Value from a Function
• The function definition must be placed before the
To use a function to calculate a value use the return command command that calls the function.
along with a variable or value. • One convention is to place all of the function
function Area(Width, Length) { definitions in the <head> section.
var Size = Width*Length; • A function is executed only when called by another
return Size; JavaScript command.
} • It’s common practice for JavaScript programmers to
– the Area function calculates the area of a rectangular region create libraries of functions located in external files.
and places the value in a variable named “Size”
– the value of the Size variable is returned by the function

55 56

14
11/16/2017

Working with Conditional Statements Comparison, Logical and Conditional Operators

if (condition) { To create a condition, you need one of three types of operators:


JavaScript Commands – a comparison operator compares the value of one element
} with that of another, which creates a Boolean expression
– condition is an expression that is either true or false that is either true or false
– if the condition is true, the JavaScript Commands in the – a logical operator connects two or more Boolean
command block are executed expressions
– if the condition is not true, then no action is taken – a conditional operator tests whether a specific condition is
true and returns one value if the condition is true and a
different value if the condition is false

57 58

An Example of Boolean Expressions Comparison Operators

• x < 100;
– if x is less than 100, this expression returns the value true;
however, if x is 100 or greater, the expression is false
• y == 20;
– the y variable must have an exact value of 20 for the
expression to be true
– comparison operator uses a double equal sign (==)

59 60

15
11/16/2017

A Logical Operator A Conditional Operator


• The logical operator && returns a value of true only if tests whether a specific condition is true and returns one value if
all of the Boolean expressions are true. the condition is true and a different value if the condition is false.
– Message = (mail == “Yes”) ? “You have mail”: “No mail”;
– tests whether the mail variable is equal to the value “Yes”
• if it is, the Message variable has the value “You have
mail”;
• otherwise, the Message variable has the value “No
mail”.

61 62

Using an If...Else Statement if...else Conditional Statement


[Link]("Today is " + ThisMonth +
if (condition) {
"/“+ThisDay+"/"+ThisYear+"<br />");
JavaScript Commands if true
} else if (DaysLeft > 0) {
JavaScript Commands if false [Link]("Only "+DaysLeft+
} " days until Christmas");
– condition is an expression that is either true or false, and } else {
one set of commands is run if the expression is true, and [Link]("Happy Holidays");
another is run if the expression is false
}

Today is 12/08/2010
Only 17 days until Christmas

63

16
11/16/2017

Working with Program Loops The For Loop

• A program loop is a set of instructions that is • The For loop allows you to create a group of commands to be
executed repeatedly. executed a set number of times through the use of a counter
that tracks the number of times the command block has been
• There are two types of loops: run.
– loops that repeat a set number of times before • Set an initial value for the counter, and each time the
quitting command block is executed, the counter changes in value.
– loops that repeat as long as a certain condition is • When the counter reaches a value above or below a certain
stopping value, the loop ends.
met

65 66

The For Loop ….

for (start; condition; update) {


JavaScript Commands
}
– start is the starting value of the counter
– condition is a Boolean expression that must be true for the
loop to continue
– update specifies how the counter changes in value each
time the command block is executed

67

17
11/16/2017

Specifying Counter Values in a For Loop

The While Loop

• The While loop runs a command group as long as a specific


condition is met, but it does not employ any counters.
• The general syntax of the While loop is:
while (condition) {
JavaScript Commands
}
– condition is a Boolean expression that can be either true
or false

71

18
11/16/2017

Using Arrays

• An array is an ordered collection of values referenced by a


single variable name.
• The syntax for creating an array variable is:
var variable = new Array(size);
– variable is the name of the array variable
– size is the number of elements in the array (optional)
• To populate the array with values, use:
variable[i]=value;
where i is the ith item of the array. The 1st item has an index
value of 0.

74

Using Arrays…. Javascripts Objects and Methods


To create and populate the array in a single statement, use:  In the context of Javascript:
var variable = new Array(values); ◦ An object is a collection of properties and methods
– values are the array elements enclosed in quotes and which can be viewed, modified and interacted with.
separated by commas  A simple example of property is color, which is rather easy to
– var MonthTxt=new Array(“”, “January”, “February”, visualize.
“March”, “April”, “May”, “June”, “July”, “August”,  They can be directly manipulated by referring to the object and
“September”, “October”, “November”, “December”); the property by name and then setting its value.
• January will have an index value of “1”.  For example, the background color of a page can be changed
as:
[Link] = “blue”;

75 76

19
11/16/2017

• In the object-oriented paradigm, methods • Methods which are defined on an object give
refer to functions that can be used to the range of choices available for interacting
manipulate objects and their properties. with the object. Some examples:
– Example: The method write(), which when – A window object can be opened or closed using
invoked on the document object, causes a specific the open() and close() methods respectively.
string of characters to be outputted. – A form object has a submit() method which
• [Link] (“Hello Good Day”); transmits the contents of the form to the web
server.

77 78

Data validation
 The sequential list of a user’s path through a number • Javascript can be used for client-side
of URLs is represented by the history object, which
has forward() and backward()methods to move
validation of data entered in HTML forms.
through the list. – Data entered can be extracted and accessed.
 Apart from the pre-defined methods, it is also – Checks can be made on the data entered.
possible to create user-defined methods. • Non-alphabetic characters in name.
◦ Control the rate with which a line of text scrolls • Non-numeric characters in roll number, age, etc.
across the screen. • Bid amount less than minimum permissible.
◦ Determine the path of an animated object across
the display.

79 80

20
11/16/2017

Example
<SCRIPT LANGUAGE="JavaScript">
function validRoll (theField) // parameter object
{
• A data validation example: var nsize = [Link];
– A student registration form. var nval = [Link];
var valid = true;
– A function checks whether the roll number is a 7- for (var i=0; i<7; i++)
digit numeric value. {
var nxtchar = [Link] (i,i+1);
• Invoked when the form is submitted.
//extracts the characters in a string between "from" and "to", not
• Check performed before form data are transmitted to including "to" itself.
server-side CGI script. if (nxtchar < "0" || nxtchar > "9")
valid = false; }
if (valid == false)
alert ("Invalid roll number: " + nval); }
</SCRIPT>

81 82

<H3> Student Registration Form </H3>


<FORM METHOD="POST" ACTION="/cgi/feedback"> Simple Animation
<P> Name: <INPUT NAME="name" TYPE="TEXT" SIZE="30"
MAXLENGTH="50">
<P> Roll Number: <INPUT NAME="rollno" TYPE="TEXT" • This example illustrates simple animation by
SIZE="7"> displaying a number of images in sequence.
<P> Courses:
<INPUT NAME="courseno1" TYPE="TEXT" SIZE="6"> – Four line images “[Link]”, “[Link]”, “[Link]”, and “[Link]”
<INPUT NAME="courseno2" TYPE="TEXT" SIZE="6"> are considered.
<INPUT NAME="courseno3" TYPE="TEXT" SIZE="6">
<P> <INPUT TYPE="BUTTON" VALUE="Submit"
> /*this: a JavaScript object that is used as shorthand to refer to the current
object in question. Used in relation to forms and method – Speed of changeover (rotation) can be controlled
definitions.*/
<INPUT TYPE="RESET"> by the user.
</FORM>

83 84

21
11/16/2017

Example: simple animation


<SCRIPT LANGUAGE="JavaScript">
• Uses the setTimeout() method of the window delay = 200;
object. number = 1;
image_seq = new Array();
for (i=1;i<5;i++)
– Schedules a piece of Javascript code to run at {
some specified time in the future. image_seq[i] = new Image();
image_seq[i].src = i + ".gif";
– Time specified in milliseconds. }
number = 1;
– Commonly used to perform animation or other function animate()
{
kinds of repetitive operations. document.line_rotate.src = image_seq[number].src;
number ++;
if (number > 4) number = 1;
}

85 86

function slow()
History Back / Forward
{
delay = delay + 25;
if (delay > 2000) delay = 2000; • Use the history object.
}
function fast()
{
– Call the back() and forward() methods to scroll
delay = delay - 25; through the recently visited pages.
if (delay < 0) delay = 0;
}
</SCRIPT>
<BODY>
<IMG NAME="line_rotate" SRC="[Link]"
('animate()', delay)" >
<FORM>
<INPUT TYPE="button" VALUE="Slow"
>
<INPUT TYPE="button" VALUE="Fast"
>
</FORM>
</BODY>
87 88

22
11/16/2017

Example: Move back/forward Browser Detection


<BODY> • This feature allows one to find out what type
<H1> Move backward and forward in history </H1> of browser is being used.
<FORM>
<INPUT TYPE="button" VALUE="BACK“ • There are two objects used for this:
– [Link] : returns the name of the
<INPUT TYPE="button" VALUE="FORWARD" browser.
– [Link] : returns the version of the
</FORM> browser.
</BODY>

89 90

Example :: browser detection Example:: password protection


<SCRIPT language="JavaScript"> <SCRIPT language="JavaScript">
var browserName = [Link]; var password;
var browserVersion = [Link]; var goodpass = “bahirdar";
if (browserName=="Netscape") password = prompt ('Enter your password:', ' ');
alert ("Hi Netscape User!" + browserVersion);
if (password == goodpass)
else
if (browserName=="Microsoft Internet Explorer") alert ('Password Correct! Click OK to enter!');
alert ("Hi, Explorer User!" + browserVersion); else
else [Link] = "[Link]
alert ("Unrecognized browser!"); </SCRIPT>
</SCRIPT>

91 92

23
11/16/2017

Page Redirection Example:: redirection


• Commonly used feature. <SCRIPT language="JavaScript">
– A previously existing web site might have moved function getgoing ()
to a new location. {
– You may want the request to be redirected to a [Link] = "[Link]
site depending on the browser type and version. }
– Manipulate the [Link] attribute. alert( "You will be redirected in five seconds.");
• An example follows. setTimeout ('getgoing()', 5000);
– Will take us to a page after 5 seconds. </SCRIPT>

93 94

Creating New Browser Window


• To open a new window, we need to call the • status = yes or no
[Link]() method. • menubar = yes or no
• copyhistory = yes or no
– [Link] (‘url to open’, ‘window name’,
attribute1, attribute2, …); – An example is shown with some of the attributes.
– Window attributes:
• width = 300
• height = 200
• resizable = yes or no
• scrollbars = yes or no
• toolbars = yes or no
95 96

24
11/16/2017

Example:: new window Including External Javascript Files


<FORM> How to do this?
<INPUT type="button" value="New Window!"  Can be done using the src attribute in the
<SCRIPT> tag.
('[Link]  Example:
'mywindow','width=400', 'height=200', <SCRIPT src=“../../codes/[Link]”>
'toolbar=yes', 'status=yes')"> </SCRIPT>
</FORM> ◦ Behaves exactly as if the contents of the specified
Javascript file appeared directly between the tags.

97 98

Using Cookies
• JavaScript provides some limited, persistent storage, called
cookies:
 Advantages: – A cookie is a small amount of named data stored by the
web browser and is associated with a particular web page
◦ Less code has to be written, and stored. or web site.
◦ Commonly used Javascript code can be shared – Serves to give the web browser the capability to
among a number of pages. memorize something.
– By default, cookies are destroyed when the browser
 Only a single copy needs to be stored on the web server.
window is closed, unless you explicitly set the expires
◦ Such Javascript files can be cached by the browser, attribute.
thereby allowing faster loading of the pages. • To persist a cookie, set the expires attribute to a
future date.
◦ The URL specified in the src attribute can refer to
• To delete a cookie, set the expires attribute to a past
other web servers also. date.

99 100

25
11/16/2017

Cookies….
 Javascript can manipulate cookies using the
“cookie” property of the “document” object. ◦ In addition to a name and value, each cookie has
◦ It is a string property that allows one to read, optional attributes:
create, modify, and delete cookies associated  expires : specifies the cookie’s lifetime.
with the current web page.  path : web pages with which it is associated.
• secure : a Boolean value; if set, cookies are transmitted
• In simple terms, we create a cookie like this:
using HTTPS.
[Link] = "name=value; expires=date;
– If the "secure" parameter is set, the cookie can only be sent to
path=path; domain=domain; secure"; a Secure Sockets Layer (SSL) server which would have a URL
...and retrieve all our previously set cookies like this: like: [Link]
It uses "HTTPS" for the protocol rather than "HTTP".
var x = [Link];

101 102

Cookie Quantities Setting a cookie


The maximum number of cookies and sizes are listed below: • To set a cookie, we set
Total cookies on a browser - 300.

– Total cookies from one server or domain - 20.
the [Link] property to a string
– The largest cookie size - 4Kb containing the properties of the cookie that
– The least recently used cookies are discarded first when more room we want to create:
for cookies is required.
[Link] = "name=value; expires=date; path=path;
domain=domain; secure";

• Example of cookie setting:


• [Link] = "username=John; expires=15/02/2012 00:00:00";
– This code sets a cookie called username, with a value of "John", that expires on Feb 15th, 2012

103 104

26
11/16/2017

JavaScript code (delete the cookie) Introducing Javascript Language Objects


• Objects
function deleteCookie() { – Attributes
if ([Link]) { – Behaviors
// Get a date and set it to last year – Encapsulate date and methods
var expDate = new Date(); – Property of information hiding
[Link]([Link]() - 1); – Details hidden within the objects themselves
[Link] = "username=" + "" + ";" + • The built-in objects not related to the documents
"expires=" + [Link](); located in the current window are known as language
objects.
}
}
• Language objects are widely used for data processing
in JavaScript.

105 106

String Object
• The String Object
• JavaScript supports the following built-in language objects: • Is one of the highest-level language objects in the
JavaScript object hierarchy.
• The String object • Can be created by assigning a string value to a
• The Array object variable or a property.
• The Date object • JavaScript’s string and character-processing
• The Math object capabilities
• Appropriate for processing names, addresses,
credit card information, etc.
– Characters
• Fundamental building blocks of JavaScript
programs
– String
107 • Series of characters treated as a single unit 108

27
11/16/2017

Methods of the String Object Methods of the String Object…


Method Description slice( start, end ) Returns a string containing the portion of the string from index start
through index end. If the end index is not specified, the method returns a
charAt( index ) Returns a string containing the character at the specified index. If there is
no character at the index, charAt returns an empty string. The first string from the start index to the end of the source string. A negative end
character is located at index 0. index specifies an offset from the end of the string starting from a
charCodeAt( index ) Returns the Unicode value of the character at the specified index. If there is position one past the end of the last character (so –1 indicates the last
no character at the index, charCodeAt returns NaN (Not a Number). character position in the string).
split( string ) Splits the source string into an array of strings (tokens) where its string
concat( string ) Concatenates its argument to the end of the string that invokes the method. argument specifies the delimiter (i.e., the characters that indicate the end
The string invoking this method is not modified; instead a new String is of each token in the source string).
returned. This method is the same as adding two strings with the string substr( Returns a string containing length characters starting from index start in
concatenation operator + (e.g., [Link]( s2 ) is the same as s1 + start, length ) the source string. If length is not specified, a string containing characters
s2).
fromCharCode( from start to the end of the source string is returned.
Converts a list of Unicode values into a string containing the
value1, value2, ) substring( Returns a string containing the characters from index start up to but not
corresponding characters.
start, end ) including index end in the source string.
indexOf( Searches for the first occurrence of substring starting from position index
substring, index ) toLowerCase() Returns a string in which all uppercase letters are converted to lowercase
in the string that invokes the method. The method returns the starting index
of substring in the source string or –1 if substring is not found. If the index letters. Non-letter characters are not changed.
argument is not provided, the method begins searching from index 0 in the toUpperCase() Returns a string in which all lowercase letters are converted to uppercase
source string. letters. Non-letter characters are not changed.
lastIndexOf( Searches for the last occurrence of substring starting from position index toString() Returns the same string as the source string.
substring, index ) and searching toward the beginning of the string that invokes the method. valueOf() Returns the same string as the source string.
The method returns the starting index of substring in the source string or –
1 if substring is not found. If the index argument is not provided, the
method begins searching from the end of the source string.
109 110

Methods of the Date object.


Date Object Method
getDate()
getUTCDate()
Description
Returns a number from 1 to 31 representing the day of the month in local time or UTC, respectively.

getDay() Returns a number from 0 (Sunday) to 6 (Saturday) representing the day of the week in local time or UTC,
getUTCDay() respectively.

• Provides methods for date and time getFullYear()


getUTCFullYear()
Returns the year as a four-digit number in local time or UTC, respectively.

manipulations getHours()
getUTCHours()
Returns a number from 0 to 23 representing hours since midnight in local time or UTC, respectively.

• The Date Object is used to extract parts of date getMilliseconds()


getUTCMilliSeconds()
Returns a number from 0 to 999 representing the number of milliseconds in local time or UTC, respectively.
The time is stored in hours, minutes, seconds and milliseconds.

and time. getMinutes() Returns a number from 0 to 59 representing the minutes for the time in local time or UTC, respectively.
getUTCMinutes()
getMonth() Returns a number from 0 (January) to 11 (December) representing the month in local time or UTC,
getUTCMonth() respectively.
getSeconds() Returns a number from 0 to 59 representing the seconds for the time in local time or UTC, respectively.
getUTCSeconds()
getTime() Returns the number of milliseconds between January 1, 1970 and the time in the Date object.

getTimezoneOffset() Returns the difference in minutes between the current time on the local computer and UTC—previously
known as Greenwich Mean Time (GMT).

setDate( val ) Sets the day of the month (1 to 31) in local time or UTC, respectively.
setUTCDate( val )

111 112

28
11/16/2017

Methods of the Date object….. Methods of the Date object…..


Method Description Method Description
setFullYear( y, m, d ) Sets the year in local time or UTC, respectively. The second and third
setUTCFullYear( y, m, d ) argument is not specified, the current value in the Date object is used.
arguments representing the month and the date are optional. If an optional
setTime( ms ) Sets the time based on its argument—the number of elapsed milliseconds
since January 1, 1970.
setHours( h, m, s, ms ) Sets the hour in local time or UTC, respectively. The second, third and fourth
setUTCHours( h, m, s, ms )
arguments representing the minutes, seconds and milliseconds are optional. If toLocaleString() Returns a string representation of the date and time in a form specific to the
an optional argument is not specified, the current value in the Date object is computer’s locale. For example, September 13, 2001 at 3:42:22 PM is
used.
represented as 09/13/01 15:47:22 in the United States and 13/09/01
15:47:22 in Europe.
setMilliSeconds( ms ) Sets the number of milliseconds in local time or UTC, respectively.
setUTCMilliseconds( ms ) toUTCString() Returns a string representation of the date and time in the form: 19 Sep 2001
setMinutes( m, s, ms ) Sets the minute in local time or UTC, respectively. The second and third 15:47:22 UTC
setUTCMinutes( m, s, ms )
arguments representing the seconds and milliseconds are optional. If an
optional argument is not specified, the current value in the Date object is toString() Returns a string representation of the date and time in a form specific to the
used. locale of the computer (Mon Sep 19 15:47:22 EDT 2001 in the United
setMonth( m, d ) Sets the month in local time or UTC, respectively. The second argument States).
setUTCMonth( m, d )
representing the date is optional. If the optional argument is not specified, the
current date value in the Date object is used. valueOf() The time in number of milliseconds since midnight, January 1, 1970.

setSeconds( s, ms ) Sets the second in local time or UTC, respectively. The second argument
setUTCSeconds( s, ms )
representing the milliseconds is optional. If this argument is not specified, the
current millisecond value in the Date object is used.

113 114

Common Javascript Object Common Javascript Object


• JavaScript is an object-based language that uses custom The Document object Model (DOM)
and built-in objects to create interactive Web pages. • Unlike other programming languages, JavaScript understands
• Each of JavaScript objects consist of properties and HTML and can directly access it.
methods. • JavaScript uses the HTML Document Object Model to
• JavaScript objects are used to manipulate the components manipulate HTML.
of a Web page. • The DOM is a hierarchy of HTML things.
• Levels of the DOM are dot-separated in the syntax.

115 116

29
11/16/2017

Document Object Model


Document Object Model
• window object
– At the very top of the hierarchy is the window
– area of the browser window where HTML documents appear
– In a multiple-frame environment,each frame is also a window
• navigator object
– This is the closest your scripts come to accessing the browser
program, primarily to read the brand and version of browser that
holds the current document
– This object is read-only, protecting the browser from inappropriate
manipulation by rogue scripts.
• screen object
– This is another read-only object that lets scripts learn about the
physical environment in which the browser is running. For example,
resolution

Document Object Model What Defines an Object?


• Properties
• history object – collection of characteristics that defines it
– <input type=“button” name=“txt1”>
– Although the browser maintains internal details about the
browser’s recent history. Example, Back n Forward – Input is the object, type and name are properties, button and txt1

• location object • Methods


– An action related to an object
– the primary avenue to loading a different page into the
– <input type=“button” name=“b1” value=“click me”>
current window or frame
– [Link]();
• document object
• Events
– Each HTML document that gets loaded into a window – actions that take place in a document, usually as the result of user
becomes a document object activity
– The document object contains the content that you are – <input type=“button” name=“b1” value=“click me”
likely to script you for the click’)”>

30
11/16/2017

The Window Object Window properties


• [Link](“ message”)
• The most common way to access Window properties – Generates a dialog box to display a message
and methods is: • [Link](“message”)
[Link]; [Link](arg); – Generates a dialog box with confirmation message with OK and
CANCEL buttons.
• The current window can be referenced using the – It returs True or False based on the button clicked.
keyword self. If([Link](“Are you sure you want to close this window?”))
[Link]();
[Link]  [Link]; • [Link](“Message”)
• To create a new Window: – displays a message that you set and provides a text field for the user
to enter a response
Var winName = [Link](“URL”, “ref”, “Height=value, Var name=[Link](“What is your name?”)
width=value”) if(name)
• Later to close the new window: alert(“Welcome “+name);
– [Link]();

The Document Object


• holds the real content of the page
• Properties and methods of the document
object generally affect the look and content of
the document that occupies the window
• Accessing document properties n methods
– [Link];
– [Link](parameters);
• The window reference is optional when the
script is accessing the document object

31
11/16/2017

Document properties Document object methods


Forms Property: [Link](“string”)
– document object contains a property—[Link]—whose value
is an array of all form element objects in the document – create content in a page as it loads
– Three ways to reference forms: – requires one string parameter which may include html tags
• [Link][0]
• [Link][“formName”]
– issued to the current page opens a new stream that
• [Link] immediately erases the current page
Images Property: [Link]()
– maintain a collection (array) of images inserted into the document by
way of <img> tags.
– Companion method to [Link]() to close the
– If([Link]){ output stream
//statements dealing with images – [Link]() issued after this will replace the current
} page content

Document object methods Document object methods


<html><head><title>Writing to Same Doc</title> <script type=”text/javascript”>
var newWindow;
<script type=”text/javascript”> function makeNewWindow() {
function reWrite() { newWindow = [Link](“”,””,”status,height=200,width=300”);
}
// assemble content for new window function subWrite() {
var newContent = “<html><head><title>A New Doc</title></head>”; // make new window if someone has closed it
newContent += “<body bgcolor=’aqua’><h1>This document is brand new.</h1>”; if ([Link]) {
newContent += “Click the Back button to see original document.”; makeNewWindow();
newContent += “</body></html>”; }
// bring subwindow to front
// write HTML to new window document [Link]();
[Link](newContent); // assemble content for new window
var newContent = “<html><head><title>A New Doc</title></head>”;
[Link](); // close layout stream newContent += “<body bgcolor=’coral’><h1>This document is brand new.</h1>”;
} newContent += “</body></html>”;
</script> </head> // write HTML to new window document
[Link](newContent);
<body> [Link](); // close layout stream
<form> } </script>
<input type=”button” value=”Replace Content” <body > <form>
</form> </body> </html> <input type=”button” value=”Write to Subwindow” > </form>c</body>

32
11/16/2017

Exerices Forms and Form Elements


• Write JS code to:
– Replace the current document
– Add another form
– And event handlers to each element
– Create a new window and with a form
– Replace the form on the new window with
another form based on the user preference
• How about appending a text to the current
document without replacement?

Forms and Form Elements Forms and Form Elements


Form object: [Link][]
– Using the original DOM Level 0 syntax, you can reference a – browser maintains a list of all control elements within a
form object either by its position in the array of forms
form as an array of elements
contained by a document or by name
– If only one form appears in the document, it is still a [Link][0].elements[0]
member of an array (a one-element array) – generally more efficient to create references to elements
[Link][0].otherObjectsWithinForm directly, using their names
[Link] [Link]
[Link][“formName”].otherObjectsWithinForm – We can loop thru the elements as an array
Accessing form properties: var form = [Link][0];
– can set attributes for name, target,action, method, and for (var i = 0; i < [Link]; i++) {
enctype if ([Link][i].type == “text”) {
[Link][0].action = “[Link] [Link][i].value = “”; } }

33
11/16/2017

Forms and Form Elements Forms and Form Elements


Form Controls as Objects Form Controls as Objects
– Input, textArea, select – following sample references to the text input
– reference as a hierarchy starting with the control are all valid
document, through the form, and then to the [Link]
control [Link][0]
[Link] [Link][“entry”]
– Consider the following simple form [Link][‘searchForm”].elements[0]
<form name=”searchForm” action=”cgi-bin/[Link]”> [Link][“searchForm”].elements[“entry”]
<input type=”text” name=”entry”> [Link][“searchForm”].entry
<input type=”submit” name=”sender” value=”Search”> [Link][0].elements[0]
</form>
[Link][0].elements[“entry”]
[Link][0].entry

Text-related input objects Text-related input objects


– For visible text elements (text, password, textArea) some <html>
<head>
of the event handlers are: <title>Text Object value Property</title>
• Giving the field a focus - onFocus <script type=”text/javascript”>
• Changing the text – onChange function upperMe() {
– The most common property is value to retrieve the input var field = [Link][0].converter;
var upperCaseVersion = [Link]();
– To retrieve the input from a text field named txt1 and store [Link] = upperCaseVersion; }
on a variable: </script> </head>
<body>
Var myString = [Link][0].[Link];
<form false”>
– Change the text and display it <input type=”text” name=”converter” value=”sample”
> [Link] = [Link](); </form>
</body> </html>

34
11/16/2017

Other form elements


Exercies
• How to retrieve a text? • Button
– The most useful event of the button object is click event
• Process input and display result
<input type=button js statements”>
• Password processing – Methods:
• blur() - Takes the focus away from the radio button.
• click() - This function acts as if the user clicked the button.
• focus() - Gives the focus to the button
– Properties:
• form - The form object that includes the button.
• name - The name of the button.
• type - The type of element which is button, submit, or reset.
• value - The value of the button that appears on the button.

Other form elements Other form elements


• Checkbox • Radio
– Check/click is the useful event
– all radio buttons in a group should have the same
– Properties
• checked - The value is true when the button is checked. name
• defaultChecked - Is true if the button is checked by default. – The browser maintains an array with the same
• form - The form object that includes the checkbox button. name
• name - The name of the checkbox button.
• type - The type of element which is checkbox. – [Link]
• value - The value of the button. • returns number of radio buttons in that group
– Methods
• blur() - Takes the focus away from the checkbox. – [Link][0].property
• click() - This function acts as if the user clicked the checkbox. This • returns the property of the first element
function may be used to:
– undo any user action on a checkbox <input type=radio name=gender value=male>
– link the clicking of multiple checkboxes together.
<input type=radio name=gender value=female>
• focus() - Gives the focus to the checkbox.

35
11/16/2017

Other form elements Other form elements


• Radio
– Properties • Option
– Contains an array of options
• checked - The value is true when the button is checked.
[Link][i].value
• defaultChecked - Is true if the button is checked by default.
[Link][i].text
• form - The form object that includes the radio button.
• name - The name of the radio button. – Properties
• type - The type of element which is radio. • defaultSelected - Is a boolean value determining whether the
option is selected by default. Read only.
• value - The value of the button.
• index - The index of the option in the list of selections. Read only.
– Methods • selected - Determines if the option is currently selected. This
• blur() - Takes the focus away from the radio button. boolean value is read/write.
• click() - This function acts as if the user clicked the button. • text - The text used to describe the option.
• focus() - Gives the focus to the radio button • value - The value sent to the server if the option was selected.
for (var i = 0; i < [Link]; i++) { • prototype - Used to create additional properties.
if ([Link][i].checked) { break; } } – Methods
var selected = [Link][i].value • blur()- Remove the focus from the option.
• focus() - Give the focus to the option

Other form elements Other form elements


• TextArea
• Select – Properties
– Properties • defaultValue - The text string value that is initially displayed.
• form - The form that contains the selection list. • form - The form object that includes the textArea object.
• name - The name of the textArea object
• length - The number of elements contained in the options array
• type - The type of element which is textarea.
• name - The name of the selection list.
• value - The value of the textArea object.
• options - An array each of which identifies an options that may be • rows - The number of rows displayed in the text area.
selected in the list
• cols - The number of columns displayed in the text area.
• selectedIndex - Specifies the current selected option within the • Wrap may be set to one of the following values:
select list – OFF - Default, lines are not wrapped.
• type - Type is "select". – PHYSICAL - Wrap lines and place new line characters where the line
wraps.
– Methods
– VIRTUAL - Wrap lines on the screen, but receive them as one line.
• blur() - Removes the input focus from the selection list.
– Methods
• focus() - Gives the input focus to the selection list.
• blur() - Takes the focus away from the textarea object.
• focus() - Gives the focus to the textarea object.
• select() - Selects the contents of the textarea.

36
11/16/2017

Event handlers Event handlers


onAbort A user clicks the Stop button while an image is onLoad The web page is loading into the browser
loading
onMouseDown The mouse button is pressed
onBlur An element loses focus
onMouseMove The mouse pointer moves
onChange An element changes…e.g. select another option,
onMouseOut The mouse pointer moves off the object
writing/deleting a text
onMouseOver The mouse pointer moves over the object
onClick The mouse button is pressed and released
onMouseUp The mouse button is released
onDblClick The mouse button is pressed and released
onMove A window is moved
onError An error occurs
onReset A form is reset
onFocus An element receives forcus
onResize A window is resized
onKeyDown A key is pressed
onSelect A text is selected in a textbox or text area
onKeyPress A key is pressed and released
onSubmit A form is submitted
onKeyUp A pressed key is released onUnload The browser moves on to another page

Passing form data and elements


Reminder • We can pass the object itself or only a specific
property
Event – is an action by the user
• To pass the object, use the key word this
e.g. click mouse, press a key <input type=text > – returns the textbox object
Event handler – is a method/function of javascript <input type=text > objects that responds to events – returns the form as an object
– form is a property of this
e.g. onClick(), onKeyPress()
• To pass a property use the complete reference
<input type=text
>

37
11/16/2017

Passing form data and elements Submitting and Prevalidating forms


• A script statement to submit a form is using form’s method –
• In the called function there should be a statement submit()
based on the parameter passed [Link]()
<input type=button >• If the argument is an textbox object, for example – This is equivalent to the submit button
Function myFunc(myTextbox){ • One of the objectives of javascript is validating forms before
they are submitted to the server
[Link]([Link]);
• To validate the input before submission, you can use the
} onSubmit eventhandler.
• If the argument is a form object <form checkInput()”>
<input ….>
function myFunc(myForm){ <input type = submit>
[Link]; function checkInput(){
} if (input valid)
return true;
else return false; }

Exercises
• Develop a page with student registration form
and display the information on another page
• Develop a page with a registration form for a
company and displays the information as a Strings, Math and Dates
table using a pop-up windows

38
11/16/2017

String String
• To create a string object • String methods
var hello = “Howdy” var result = [Link]();
– Change case
var hello = new String(“Howdy”)
var result = [Link]();
• Joining Strings var result = [Link]();

Var concat = string1 + string2 +…. – String search


var [Link](shortStr)
var msg = “Four score”; – if longStr contains shortStr, it returns the starting index of shortStr
in longStr. Other wise, it returns -1
msg += “ and seven”;
var str = “I love programming”;
msg += “ years ago,”; [Link](‘love’) – returns 2
[Link](“javascript”) – returns -1

String Math
• String methods • Most common functions are:
var – var piVal = [Link]
• Returns the char at index within str – var larger = [Link](val1, val2)
var subStr = [Link](startIndex, endindex) – var result = [Link](val1, powVal)
• Returns the substring from strartIndex (inclusive) to – var int = [Link](floatVal)
endIndex (exclusive)
– var ran = [Link]()
• Exercise:
– var smallInt = [Link](floatVal)
– Find out some other string methods
• Exercise:
– Find out some more Math methods

39
11/16/2017

Date Date
• To create an instance of the PC’s clock • Date calculations
var today = new Date();
– The surest way is to convert all dates to
• To get an instance of the PC’s clock at a specified miliseconds and perform the operation
date or time
var someday = new Date(“date or time”); var todayInMS = [Link]();
• To extract time, date or day from the already created var nextWeekInMS = todayInMS + (60 * 60 * 24 * 7
instance * 1000);
var result = [Link](),
= [Link]()
= [Link]()
• More from table 10-1

Exercise
• Develop online calculator
• Develop an online application that takes a
date (yy,mm,dd) and returns the day (Mon,
Tue…..)
• Attach a clock to your website
• Do some more exercises on input/output,
Interaction with the user

40

You might also like