0% found this document useful (0 votes)
50 views104 pages

JavaScript Basics and Usage Guide

good pdf

Uploaded by

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

JavaScript Basics and Usage Guide

good pdf

Uploaded by

mekashfetene89
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Chapter 4

Client-Side Scripting
Using JavaScript
1
The contents to be covered are:
Introduction to JavaScript
JavaScript Syntax
JavaScript operators
JavaScript Data Types
JavaScript Pop-up boxes
 Alert, confirm and prompt.
 Conditional and switch statements, loops and functions
Event handling
Form validation/processing

2
WHAT IS JAVASCRIPT?
 JavaScript was designed to add interactivity to HTML pages
 JavaScript is a scripting language i.e. lightweight programming
language
 A JavaScript is usually embedded directly in HTML pages
 It is an interpreted language (means that scripts execute without
preliminary compilation)
 Converts code to executable format each time it runs
 Converted when browser loads a web document
3
 JavaScript is supported by all major browsers
3
JAVASCRIPT VS. JAVA

 Java Script  Java


 Interpreted (not compiled) by  Compiled on server before execution
client on client
 Object-based (code uses built-in,  Object-oriented (applets consist of
extensible objects, but no classes object classes with inheritance)
or inheritance).  Applets distinct (separate) from HTML
 Embedded in HTML. (accessed from HTML pages)

4
JAVASCRIPT VS. JAVA (2)

 JavaScript  Java
 variable data types not declared  variable data types must be declared
(loose typing) (strong typing)
 dynamic binding (object  static binding (object references must
references checked at run-time) exist at compile-time)
 security: cannot write to hard  security: multilevel control
disk  graphics library (AWT), threads,
 no graphics library, no threads, networking (sockets, RMI, etc.)
no networking 5

5
USES OF JAVASCRIPT
 Gives HTML designers a programming tool
 HTML authors are normally not programmers, but JavaScript is a
scripting language with a very simple syntax!
 Almost anyone can put small or "snippets" of code into their HTML
pages
 A JavaScript can be set to execute when something happens, like when
a page has finished loading or when a user clicks on an HTML element
 Can read and write HTML elements
 Can be used to validate data (e.g. form data) before it is submitted to a
6
server
6
USING JAVASCRIPT IN HTML

 JavaScript can be embedded in a HTML document in three ways:

1. As statements and functions using the SCRIPT tag.

2. As event handlers using HTML tags.

3. In javascript:

7
SIMPLE JAVASCRIPT PROGRAM

FileName: [Link]
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
// This is a comment in JavaScript
[Link]("<h1>Hello folks!</h1>");
</SCRIPT>
</HEAD>
<BODY>
Welcome to this class!
</BODY>
8
</HTML>
8
WRITE METHOD
[Link] directs the document object to write
the given string
Examples: Concatenate the strings and number
together and write the resulting
<script>
string out
counter = 10;
[Link]("<h1>Counter is "+counter+"</h1>");
</script>

<script>
[Link]("<IMG SRC=‘[Link]’>"); // notice the use of “ and ‘
</script>

9
HIDING JAVASCRIPT CODE (FROM OLD BROWSERS)

1. To prevent old browsers from displaying your JS code, you can do the following:
• Immediately after opening <script> tag, put a one-line HTML-style comment
without the closing characters, so that the first two lines of your script would
look like this: <script type="text/javascript" language="JavaScript"> <!--
2. At the end of your script, put the following two lines: //--> </script>
• Thus, your HTML file will contain the following fragment: <script
language="JavaScript"> <!-- Here you put your JS code. Old browsers will
treat it as an HTML comment. //--> </script>
10

10
NOSCRIPT TAG
 Use the <NOSCRIPT> tag to specify alternate content for browsers that do not support JavaScript.
 HTML enclosed within a <NOSCRIPT> tag is displayed by browsers that do not support
JavaScript.
 The following example shows a <NOSCRIPT> tag.
<NOSCRIPT>
<B>This page uses JavaScript, so you need to get a newer version of IE or Netscape!
<BR>
<A HREF="[Link]
<IMG SRC="[Link]"></B>
If you are using Navigator 2.0 or later, and you see this message, you should enable JavaScript by
on the Advanced page of the Preferences dialog box.
</NOSCRIPT>
11

11
Adding JavaScript
• There are three ways to add JavaScript commands to your Web Pages.
I. Embedding code
II. Inline code
III. External file
I. External File
• If you want to run the same JavaScript on several pages, you can write a JavaScript in an
external file.
• Save the external JavaScript file with [Link] file extension.

12
Adding JavaScript…

• The external script cannot contain the <script></script> tags!


• You can use the SRC attribute of the <SCRIPT> tag to call JavaScript code from an
external text file.
• It is called by the following tag:
<SCRIPT language = "JavaScript" SRC = "filename">
</SCRIPT>
II. Scripts in <head>
• Scripts to be executed when they are called, or when an event is triggered (generated),
are placed in functions.
• Put your functions in the head section, this way they are all in one place, and they do
not interfere with page content.
13
Adding JavaScript…
<html>
<head>
<script language="javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>
<body onload="message()">
</body>
</html> 14
Adding JavaScript…

III. Scripts in <body>


• If you do want your script to be placed inside a function, or if your script should
write page content, it should be placed in the body section.
<html>
<head> </head>
<body>
<script language="javascript">
[Link]("This message is written by JavaScript");
</script>
</body>
</html>
15
Input-Output in Java
• In JavaScript, input-output can be done in different ways:
[Link](“message to display”);
alert(“message to display”);
prompt(“message to display”, “default value”);
confirm(“message to display”);
• [Link] method writes a string to the web page.
• Anything between double quotes will be displayed as it is in the web page.
• However, if there is something out of quotes, it is evaluated as expression and
the result will be sent to the web page.

16
Simple JavaScript Pop-up Boxes
 alert

An alert box is often used if you want to make <!DOCTYPE html>


sure information comes through to the user. <html>
When an alert box pops up, the user will have <body>
<h2>JavaScript Alert</h2>
to click "OK" to proceed. <button onclick="myFunction()">Try it</button>
Syntax: [Link]("sometext"); <script>
function myFunction() {
The [Link]() method can be written alert("I am an alert box!");
}
without the window prefix. </script></body></html>
Example: alert("I am an alert box!");

17

17
<!DOCTYPE html>
confirm <html>
<body>
A confirm box is often used if you want the user
<h2>JavaScript Confirm Box</h2>
to verify or accept something. When a confirm <button onclick="myFunction()">Try it</button>
box pops up, the user will have to click either <p id="demo"></p>
"OK" or "Cancel" to proceed. If the user clicks <script>
"OK", the box returns true. If the user clicks function myFunction() {
var txt;
"Cancel", the box returns false. if (confirm("Press a button!")) {
Syntax: [Link]("sometext"); txt = "You pressed OK!";
The [Link]() method can be written } else {
without the window prefix. txt = "You pressed Cancel!";
}
Example
[Link]("demo").innerHTML = txt;
if (confirm("Press a button!")) { }
txt = "You pressed OK!"; </script>
} else { </body>
txt = "You pressed Cancel!"; </html>

18
Simple JavaScript Pop-up cont….
 eval
<!DOCTYPE html>
<html>
 eval() is a global function in JavaScript <body>
that evaluates a specified string as <h1>Demo: eval</h1>
<script>
JavaScript code and executes it.
var result;
 Itevaluates a string and
function Sum(val1, val2)
returns a value. {
 Syntax: return val1 + val2;
}
eval(stringExpression)
eval( "result = Sum(5, 5);");
 Example: eval(1+2*3) // gives
7 here alert(result);
</script>
</body>
</html> 19

19
prompt <!DOCTYPE html>
<html>
A prompt box is often used if you want the user <body>
to input a value before entering a page. <h2>JavaScript Prompt</h2>
<button onclick="myFunction()">Try it</button>
When a prompt box pops up, the user will have <p id="demo"></p>
<script>
to click either "OK" or "Cancel" to proceed after function myFunction() {
entering an input value. var txt;
var person = prompt("Please enter your name:", "Harry
If the user clicks "OK" the box returns the input Potter");
if (person == null || person == "") {
value. If the user clicks "Cancel" the box returns txt = "User cancelled the prompt.";
null. } else {
txt = "Hello " + person + "! How are you today?";
Syntax }
[Link]("demo").innerHTML = txt;
[Link]("sometext","defaultText"); }
The [Link]() method can be written </script>
</body>
without the window prefix. </html>
20
DATA TYPES
 Numbers
 1, 3.14159, -99
 Logical (Boolean) values
 true or false
 Strings
 “hello”, ‘hello’,
 null
 special keyword denoting null value

21

21
STRING LITERALS
 A string literal is zero or more characters enclosed in double (") or
single (') quotes.
 A string must be delimited by quotes of the same type; that is, either

both single quotes or double quotes. The following are examples of


string literals:
 "Hello"
 'Hello'
 "1234"
 “one line \n another line”
 '"Don\'t try that again!," I yelled.'

22

22
VARIABLES
 We use variables to hold values in our application.
 Syntax:
var myVar; // var => local variable; Otherwise, the variable is global

 JavaScript is a loosely typed language.


myVar = 33;
myVar = “Hello World”;
myVar = 33 + “Hello World”; // gets “33HelloWorld”
myVar = “Hello World” + “33”; // gets “Hello World33”

23

23
VARIABLES
 More Syntax
 var Variablename = value;
 var x = 3;

 var name = “ABC”;

 var x, y = 0;

 var x = null;

 Note: Null is: 0 (number), false (Boolean)


 There is no way to specify that a particular variable
represents an integer, a string or a floating-point (real)
number.

24

24
VARIABLE NAMES
 A JavaScript identifier or name must start with a letter or underscore
("_"); subsequent characters can also be digits (0-9). Letters include
the characters "A" through "Z" (uppercase) and the characters "a"
through "z" (lowercase).
 JavaScript is case-sensitive.
 Some examples of legal names are:
 Last_Name

 status

 _name
25

25
OPERATORS

 Arithmetic
+ (Addition, String Concatenation)
- (Subtraction, Unary Negation)
* (Multiplication)
/ (Division)
% (Modulus) (e.g., 7 % 3 gives 1)
++ (Preincrement, Postincrement) // increments a variable by 1
e.g., x = 1; alert(x++); alert (x) // displays 1, then 2
e.g., x = 1; alert(++x); alert (x) // displays 2, then 2
-- (Predecrement, Postdecrement) // decrements a variable by 1
e.g., x = 1; alert(x--); alert (x) // displays 1, then 0
e.g., x = 1; alert(--x); alert (x) // displays 0, then 0

26

26
OPERATORS (CONT...)
 Assignment Operators
= means assignment
PI = 3.14159; // var PI is assigned 3.14159
Op= (where op is one of +, -, *, /, etc.)
x += y means x = x + y
x *= y means x = x * y
x -= y means x = x - y
x /= y means x = x / y

27

27
OPERATORS (CONT...)
 Relational Operators
==, != (Equality, Inequality)
<, <=, =>, > (Arithmetic and String Comparison)
! (Logical Not)
&&, || (Logical AND, Logical OR)
?: (Conditional Selection)
e.g., x = (1 < 5)? ‘a’:’b’; // here, x gets ‘a’

28

28
OPERATOR PRECEDENCE
 The precedence of operators determines the order they are applied when
evaluating an expression. You can override operator precedence by using
parentheses.
 The precedence of operators, from lowest to highest is as follows: (Partial
Listing)
 assignment = += -= *= /= %=
 conditional ?:
 logical-or ||
 logical-and &&
 equality == !=
 relational < <= > >=
 addition/subtraction + -
 multiply/divide * / %
 negation/increment ! ++ --
 call, member () [] . 29

29
EXPRESSIONS
 An expression is any valid set of literals, variables, and
operators that evaluates to a single value.
PI = 3.14159
12 + 6
2 * PI * r
x++
x -= 3

30

30
Control Structures
 The kinds of statements that make decisions and loop around to
repeat themselves are called control structures.
 A control structure directs the execution flow through a sequence of
script statements based on simple decisions and other factors.
 JavaScript provides several kinds of control structures for different
programming situations.
 Three of the most common control structures you’ll use are if
constructions, if...else constructions, and for loops.
31

31
if (condition) {
statement[s] if true
}
Example:
if (myAge < 18) {
alert(“sorry”, you are not allowed to vote.”);
}
For all instances of myAge less than 18, the nested statement inside
the curly braces runs and displays the alert to the user.
After the user closes the alert dialog box, the script continues with
whatever statement follows the entire if construction.

32
if…else construction
 In the plain if construction, no special processing is performed when the condition
evaluates to false. But if processing must follow one of two special paths, you need the
if...else construction. The formal syntax definition for an if...else construction is as
follows:
 Syntax
if (condition) {
statements if true
} else {
statements if false
33
}
33
Loops

A loop lets a script cycle through a sequence of statements until some condition is met
(encountered).
For example, a JavaScript data validation routine might inspect every character that you
enter in a form text field to make sure that each one is a number.
Or if you have a collection of data stored in a list, the loop can check whether an
entered value is in that list.
When that condition is met, the script can break out of the loop and continue with the
next statement after the loop construction.
The most common repeat loop construction used in JavaScript is called the for loop
The formal syntax of the for loop is as follows:
for (initial expression; condition; update expression) {
statement[s] inside loop
34
}
Functions
 A user-defined or built-in set of statements that perform a specific task.
 Functions are invoked by event handlers or by statements elsewhere in the
script.
 A JavaScript function is executed when "something" invokes it (calls it).
 It can also return a value when used with the return statement.
 Syntax:
function name(param1 , param2 ..., paramN) {
statements
}
Function Invocation
The code inside the function will execute when "something" invokes (calls) the
function:
 When an event occurs (when a user clicks a button)
 When it is invoked (called) from JavaScript code
 Automatically (self invoked)

35

35
Function Return
 When JavaScript reaches a return statement, the function will stop executing.
 If the function was invoked from a statement, JavaScript will "return" to execute
the code after the invoking statement.
 Functions often compute a return value.
 The return value is "returned" back to the "caller":
Example
// Takes an endValue and returns 1+2+3+ … + endValue
function summation (endVal) {
var thesum=0;
for ( var iter = 1; iter <= endVal; iter++ )
thesum += iter;
return ( thesum ); Output:
} 15
[Link](summation(5))
36
A Simple Function
<HTML>
<HEAD>
<SCRIPT>
function compute(form)
{
[Link] = eval([Link])
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
Enter an expression:
<INPUT TYPE="text" NAME="expr" SIZE=15 >
<INPUT TYPE="button" VALUE="Calculate" ONCLICK="compute([Link])">
<BR>
Result:
<INPUT TYPE="text" NAME="result" SIZE=15 >
</FORM>
</BODY>
</HTML> 37

37
expr

Result

38

38
expr

function compute(form)
Result {
[Link] = eval([Link])
}
39

39
Array
The JavaScript array is one of the most useful data constructions you have available.

To access an item in an array, you need to know the name of the array and the index
number.

Because index values start with zero, the total number of items of the array (as
determined by the array’s length property) is always one more than the highest index
value of the array.

Data elements inside JavaScript arrays can be any data type, including objects.

40
Creating an array
 An array is stored in a variable, so when you create an array, you assign the new array object to the variable.
 A special keyword new preceding a call to the JavaScript function that generates arrays creates space in
memory for the array.
 An optional parameter to the Array() function enables you to specify at the time of creation how many
elements of data eventually will occupy the array.
 To demonstrate the array creation process, suppose, create an array that holds the student names as follows:
var studentName = new Array(4);
The first row of the studentName array is addressed as:
studentName[0]
To assign the string of value to the array, We use a simple assignment operator:
studentName[0] = “Ayele”;
studentName[1] = “Beshatu”;
studentName[2] = “Garuma”;
studentName[3] = “Burte”;

41
Accessing array data

The array index is the key to accessing an array element.


The name of the array and an index in square brackets evaluates to the content of that
array location.
For example, after the studentName array is built, a script can display an alert with
Garuma’s name in it with the following statement:
alert(“The student is “ + studentName [2] + “.”);

42
Event Handling

 JavaScript reacts to events. because events are inherently part of


almost all Web pages and they make the pages interactive and
dynamic.
 JavaScript events are asynchronous, meaning that they can happen at

any time.
 e.g.,

 <INPUT type=“button” VALUE=“button1”


 onClick=“computeSomething()”>
 Events are triggered in the browser primarily by user actions such as

button click, page load, form submit.

43

43
EVENT HANDLERS
 The following event handlers are available in JavaScript:
 onAbort
• onMouseDown
 onBlur
• onMouseMove
 onChange • onMouseOut
 onClick • onMouseOver
 onDragDrop • onMouseUp
 onError • onMove
 onFocus • onReset
 onKeyDown • onResize
 onKeyPress • onSelect
 onKeyUp • onSubmit
• onUnload
 onLoad
44

44
Event Event Handler Description
Load onLoad Browser finishes loading a Web document
Unload onUnload Visitor requests a new document in the browser window
Mouseover onMouseOver Visitor moves the mouse over some object in the document window
Mouseout onMouseOut Visitor moves the mouse off of some object in the document window
MouseDown onMouseDown A mouse button was pressed
MouseMove onMouseMove The mouse moved
MouseUp onMouseUp The mouse button was released
Select onSelect Text has been selected.
Click onClick Visitor clicks the mouse button
Focus onFocus Visitor gives focus to or makes active a particular window or form element by clicking on
it or tabbing to it
Blur onBlur A form field lost the focus (user moved to another field)
Change onChange Visitor changes the data selected or contained in a form element
Submit onSubmit Visitor submits a form
Reset onReset Visitor resets a form
Abort onAbort An image failed to load
Change onChange The contents of a field has changed
DblClick onDblClick User double-clicked on this item
Error onError An error occurred while loading an image
Keydown onKeyDown A key was pressed
KeyPress onKeyPress A key was pressed or released
KeyUP onKeyUp A key was released
45
Example: a program that adds or subtracts two numbers when respective button is clicked
<html>
<head>
<script language="JavaScript">
function adder(num1, num2)
{
var sum = 0;
sum = num1 + num2;
[Link]("The sum is " + sum);
}
function subtractor(num1, num2)
{
var difference = 0;
difference = num1 - num2;
[Link]("The difference is " + difference);
}
</script>
</head>
<body>
<form name="event_example">
<input type="button" value="add" name="add" onClick="adder(10,30)">
<input type="button" value="subtract" name="subtract" onClick="subtractor(20,50)">
<a href=“” onclick=“adder(30,40”> Add </a>
</form>
</body>
</html>
46
EVENT HANDLERS (CONT...)
 onAbort
 An abort event occurs when a user aborts the loading of an image (for example
by clicking a link or clicking the Stop button)
 onBlur
 A blur event occurs when a select, text, or textarea field on a form loses focus.
 onChange
 A change event occurs when a select, text, or textarea field loses focus and its
value has been modified.
 onClick
 A click event occurs when an object on a form is clicked.

47

47
EVENT HANDLERS (CONT...)
 onError
 An error event occurs when the loading of a document or image causes an
error
 onFocus
 A focus event occurs when a field receives input focus by tabbing with the
keyboard or clicking with the mouse.
 onKeyDown, onKeyPress, onKeyUp
 A keyDown, keyPress, or keyUp event occurs when a user depresses a key,
presses or holds down a key, or releases a key, respectively

48

48
EVENT HANDLERS (CONT...)
 onLoad
 A load event occurs when Navigator finishes loading a window or all
frames within a <FRAMESET>.
 Examples
 In the following example, the onLoad event handler displays a greeting message

after a web page is loaded.


 <BODY onLoad="[Link]('Welcome to my home page!')">

onMouseDown, onMouseMove, onMouseOut, onMouseOver, and


onMouseUp
 A MouseDown, MouseMove, MouseOut, MouseOver, or MouseUp event occurs when
a user depresses a mouse button, moves a cursor, moves a cursor out of a link or
image map, moves a cursor over a link, releases a mouse button, respectively

49

49
EVENT HANDLERS (CONT...)
 onMouseOver
 A mouseOver event occurs once each time the mouse pointer moves over
an object from outside that object.
 Example

<A HREF="[Link]
onMouseOver="[Link]=‘A Good Place …!'; return true">
Click me</A>
Return true tells the browser not to perform its own event handling
routine of displaying the link’s URL in the status bar

50

50
EVENT HANDLERS (CONT...)
 onSelect
 A select event occurs when a user selects some of the text within
a text or textarea field.
 onSubmit

 A submit event occurs when a user submits a form


 onUnload

 An unload event occurs when you exit a document.

51

51
FORM VALIDATION
FileName: [Link]
<html><head><script <body>
language="JavaScript"> <form name="first">
function test1(form) { Enter your name:<br>
if ([Link] == "")
<input type="text"
alert("Please enter a string!")
name="text1">
else {
alert("Hi "+[Link]+"!
<input type="button"
Form input ok!"); name="button1" value="Test
} Input"
} onClick="test1([Link])">
function test2(form) { <P>
if ([Link] == "" || Enter your e-mail address:<br>
[Link]('@') <input type="text"
== -1)
name="text2">
alert("No valid e-mail
address!"); <input type="button"
else alert("OK!"); name="button2" value="Test
52
} Input"
// --> onClick="test2([Link])">
52
</script></head> </body>
FORM VALIDATION (2)
FileName: [Link] <BODY>
<HTML> <P>
<HEAD> <HR><FORM NAME="myform"
<SCRIPT onSubmit="checkit()"></P>
LANGUAGE="JavaScript">
function checkit() {
<P>Enter a number between 1
var strval =
and 9: <INPUT TYPE="text"
[Link]
e; NAME="mytext" VALUE=""
SIZE="10"></P>
var intval = parseInt(strval);
if ( intval > 0 && intval < 10
){ <P><BR>
return(true); <INPUT
} else { TYPE="submit"></FORM>
alert("Input value " + <HR></P>
strval + " is out of range");
return(false);
</BODY>
}
</HTML> 53
}
</SCRIPT> 53
</HEAD>
Introduction to XML
 XML(Extensible Markup Language): lets you create text documents that can hold data in a structured way.

 It helps information systems share structured data

 Application and platform independent.

 Allows various type of data.

 Allows user defined tags

XML Basics

 XML permits document authors to create markup (i.e. a text based notation for describing data) for virtually
any type of information.

 This enables document authors to create entirely new markup languages for describing any type of data, such
as mathematical formulas, software – configuration instruction, chemical molecular structures, music, news
and etc.

 XML describes data in a way that both human beings and computers can understand.
54
Example:
<?xml version = “1.0”?>
<player>
<firstName>Hebron</firstName>
<lastName>Fergusen</lastName>
<score>3.00</score>
</player>
XML documents contain text that represents content (i.e. data), such as Hebron, and elements that
specify the document’s structure, such as firstName .
XML documents delimit elements with start tags and end tags. A start tag and end tag consists of
the element name in angle brackets (e.g. <player> and </player>)

55
Advantages of use XML
Simpler version of standard to Generalized Markup Language(SGML).
Easy to understand and read.
Support by large number of platforms.
Used across open standard.
Components of XML.
Declaration
Attribute
Tags
Elements
comments
57
Cont’d
Declaration: Tags:
The first line in document. Text in between < and >
Provide information to the Tags and data stored together.
parser. Data is self-descriptive and easy
Contain three name-value pairs: to understand.
Version(common)
Encoding (defaults to UTF-8)
Standalone(rare)

58
Cont’d
Elements: Attributes:
Basic building block of an XML file. Provide information about the
Text between start and end tag. elements.
Document contain one root element. Name-value pairs:
 Single or double quotes to encode
Can contain nested elements.
values.
 Attribute names are unique
within the same element.

59
Cont’d
Comments:
Appear anywhere in document
Start tag <!--
End tag --!>
Contents inside of comment are not parsed.

60
JavaScript Objects
3.2 Working with JavaScript Objects
• JavaScript has many built-in objects that you can use to perform different
activities.
• Every time you load a page into web browser, the JavaScript interpreter
creates certain Objects based on how the HTML is written.
• This minimal Object set is comprised of the navigator, window, document,
location, and history Objects.
• Depending on what's contained in the page, there can obviously be other
Objects that are also generated by the interpreter.
• All of these Objects exist in an Object hierarchy that can be accessed by
calling on the Object with dot notation.
• The following chart shows the structure.

61
JavaScript Objects and Events…
Object Properties and Methods
• All objects have properties and methods that are associated with them.
• All objects have the same properties, but the property values differ from objects to
objects.
• All objects have the same methods, but the methods are performed at different times.
• A Property of an object is basically a predefined variable that you can assign a value to with simple
dot notation Syntax like this:
[Link] = value

For instance, A car has properties like weight and color, and methods like start and stop:

Properties Methods
[Link]=850kg [Link]()
62
[Link]=blue [Link]()
JavaScript Objects and Events…
• A Method of an object is a predefined function that is assigned to an
Object by browser.
• You invoke a Method on an Object with the same dot notationlike this:
[Link]()
• Suppose you want to give focus to the window at some point in your
Script.
• You do that by referencing the window Object and calling the focus()
method like this:
[Link]();

63
JavaScript Objects and Events…
2. JavaScript Objects
• JavaScript has many built-in objects that you can use to perform different
activities.
• The most important objects are:
• Math
• String
• Date
• History
• Document
• Number

64
JavaScript Objects and Events…
2.1 Math Object
• The predefined Math object has properties and methods for
mathematical constants and functions.
• For example, the Math object’s PI property has the value of pi
(3.141...), which you would use in an application as [Link]
• Similarly, standard mathematical functions are methods of Math.
• These include trigonometric, logarithmic, exponential, and other
functions.

• For example, if you want to use the trigonometric function sine, you
would write:
[Link](1.56)
• Note that all trigonometric methods of Math take arguments in
radians.
65
JavaScript Objects and Events…
Property Value Description

Math.E 2.718281828459045091 Euler’s constant

Math.LN2 0.6931471805599452862 Natural log of 2

Math.LN10 2.302585092994045901 Natural log of 10

Math.LOG2E 1.442695040888963387 Log base-2 of E

Math.LOG10E 0.4342944819032518167 Log base-10 of E

[Link] 3.141592653589793116 π

Math.SQRT1_2 0.7071067811865475727 Square root of 1/2

Math.SQRT2 1.414213562373095145 Square root of 2

66
Method Syntax Returns
[Link](val) Absolute value of val
[Link](val) Arc cosine (in radians) of val
[Link](val) Arc sine (in radians) of val
[Link](val) Arc tangent (in radians) of val
Math.atan2(val1, val2) Angle of polar coordinates x and y
[Link](val) Next integer greater than or equal to val
[Link](val) Cosine of val
[Link](val) Euler’s constant to the power of val
[Link](val) Next integer less than or equal to val
[Link](val) Natural logarithm (base e) of val
[Link](val1, val2) The greater of val1 or val2
[Link](val1, val2) The lesser of val1 or val2
[Link](val1, val2) Val1 to the val2 power
[Link]() Random number between 0 and 1
[Link](val) N+1 when val >= N.5; otherwise N
[Link](val) Sine (in radians) of val
[Link](val) Square root of val
[Link](val) Tangent (in radians) of val 67
JavaScript Objects and Events…
• Example:
[Link](3.5); // result: 4
[Link](–3.5); // result: –3.
[Link](5, 2); // result: 25
[Link](1.6); //result: 1
[Link](1.6); //result: 2
[Link](90); //result: 1

68
JavaScript Objects and Events…
2.2 Date Object
• Most of your date and time work is done with the Date object.
• The basic syntax for generating a new date object is as follows:
var dateObjectName = new Date([parameters])

• The parameter can be:


new Date(“Month dd, yyyy hh:mm:ss”)
new Date(“Month dd, yyyy”)
new Date(yy,mm,dd,hh,mm,ss)
new Date(yy,mm,dd)
new Date(milliseconds)
69
Method Value Range Description
[Link]() 0-... returns Milliseconds since 1/1/70 [Link] GMT
[Link]() 70-... returns Specified year minus 1900
returns four-digit year for 2000+
[Link]() 1970-... returns four-digit year (Y2K-compliant)
[Link]() 0-11 returns Month within the year (January = 0)
[Link]() 1-31 returns Date within the month
[Link]() 0-6 returns Day of week (Sunday = 0)
[Link]() 0-23 returns Hour of the day in 24-hour time
[Link]() 0-59 returns Minute of the specified hour
[Link]() 0-59 returns Second within the specified minute
[Link](val) 0-... sets Milliseconds since 1/1/70 [Link] GMT
[Link](val) 70-... sets Specified year minus 1900
sets four-digit year for 2000+
[Link](val) 0-11 sets Month within the year (January = 0)
[Link](val) 1-31 sets Date within the month
[Link](val) 0-6 sets Day of week (Sunday = 0)
[Link](val) 0-23 sets Hour of the day in 24-hour time
[Link](val) 0-59 sets Minute of the specified hour
[Link](val) 0-59 sets Second within the specified minute
70
JavaScript Objects and Events…
• Example: display current date and time
var today = new Date();
var date = [Link]();
var month = [Link]();
var year = [Link]();
[Link](“Today’s date: ”+date+”/”+month+”/”+year);

output:
Today’s date: 4/11/2010

• Example: to set date to some past time like birth date


var myBirthday = new Date(“September 11, 2001”);
result = [Link](); // result = 2, a Tuesday
[Link](2002); // bump up to next year
result = [Link](); // result = 3, a Wednesday 71
JavaScript Objects and Events…
2.3 String Object
• A string is any text inside a quote pair.
• A quote pair consists of either double quotes or single quotes.
• JavaScript imposes no practical limit on the number of
characters that a string can hold.

• You have two ways to assign a string value to a variable.


• The simplest is a basic assignment statement:
var myString = “Hello there.”;

• You can also create a string object using the more formal syntax
that involves the new keyword and a constructor function like:
var stringVar = new String(“characters”); 72
Method Description
charAt(index) Returns the character at the specified index.
charCodeAt(index) Returns a number indicating the Unicode value of the character at the given index.
concat(string) Combines the text of two strings and returns a new string.
indexOf(string, [start]) Returns the index within the calling String object of the first occurrence of the
specified value, or -1 if not found.
lastIndexOf(string,[start]) Returns the index within the calling String object of the last occurrence of the
specified value, or -1 if not found.
localeCompare(string2) Returns a number indicating whether a reference string comes before or after or is
the same as the given string in sort order.
length Returns the length of the string.
match(regExpression) Used to match a regular expression against a string.
replace(regExpression,replacer) Used to find a match between a regular expression and a string, and to replace the
matched substring with a new substring.
search(regExpression) Executes the search for a match between a regular expression and a specified string.
slice(startIndex [,end]) Extracts a section of a string and returns a new string.
split(delimiter [,limit]) Splits a String object into an array of strings by separating the string into substrings.
substr(start [, length]) Returns the characters in a string beginning at the specified location through the
specified number of characters.
substring(start, end) Returns the characters in a string between the two indexes into a string.
toLowerCase() Returns the calling string value converted to lower case.
toUpperCase() Returns the calling string value converted to uppercase.
toString() Returns a string representing the specified object.
73
JavaScript Objects and Events…
• Example:
var name = new String(“Konrad Zuse person who crete computer for
first time”);
[Link](“ - created the first computer”);
[Link](0,10);
[Link](“Zuse”);
[Link](“a”,”#”);
[Link]();a
• Output:
Konrad Zuse - created the first computer
Konrad Zuse
7
KONRAD ZUSE
Konr#d Zuse

74
JavaScript Objects and Events…
2.4 Document Object
• Contains information on the current document.
• Document object contains properties and methods that can be
used to access the page elements.
• Properties:
• title -Current document title. If no title is defined, title contains “Untitled.”
• location -Full URL of the document.
• lastModified -A Date object-compatible string containing the date the
document was last modified.
• bgColor -Background color, expressed as a hexadecimal RGB value (for example,
#FFFFF for white). Equivalent to the BGCOLOR attribute of the <BODY> tag.
• fgColor -Foreground (text) color, expressed as a hexadecimal RGB value
compatible with HTML syntax. Equivalent to the TEXT attribute of the <BODY>
tag.
75
JavaScript Objects and Events…
• linkColor - Hyperlink color, expressed as a hexadecimal RGB value compatible with
HTML syntax. Equivalent to the LINK attribute of the <BODY> tag.
• alinkColor - Activated hyperlink color, expressed as a hexadecimal RGB value.
Equivalent to the ALINK attribute of the <BODY> tag.
• vlinkColor – visited link color, expressed as hexadecimal RGB value
• forms[ ] - Array of form objects in the document, in the order specified in the
source. Each form has its own form object.
• [Link] - The number of form objects within the document.
• links[ ] - Array objects corresponding to all HREF links in the document, in the
order specified in the source.
• [Link] - The number of HREF links in the document.
• anchors[ ] - Array of all "named" anchors between the <A NAME=""> and </A>
tags within the document.
• [Link] - The number of named anchors in the document.
• images[] - Image objects that correspond to each image on the page.
• applets[] - Java applet objects that correspond to each applet on the page.
76
• embeds[] - Plugins object that represent each plug-in on the page.
JavaScript Objects and Events…
• Example: changing link colors
[Link] = “red”;
[Link] = “blue”;
[Link] = “green”;

• Methods:
• write("string")-Writes string to the current window. string may
include HTML tags.
• writeln("string") - Performs the same as write(), but adds a
carriage return. This affects only preformatted text (inside a
<PRE> or <XMP> tag).
• clear( ) - Clears the window.
77
• close( ) - Closes the window.
JavaScript Objects and Events…
2.5 History Object
• The history object contains a list of strings representing the URLs the client
has visited.
• You can access the history values using the history array.
• This array contains an entry for each history entry in source order; each
array entry is a string containing a URL.
var fifthEntry = [Link][4];
• You can also redirect the client to any history entry by using the go
method.
• For example, the following code loads the URL that is two entries back in
the client’s history list.
[Link](-2)

78
JavaScript Objects and Events…
• The following code reloads the current page:
[Link](0)
Properties Methods
Length back()
forward()
go()

• [Link]() – goes back to last visited page


• [Link]() – goes forward just like clicking forward button on toolbar
• [Link](location) – goes to the specified history location.

• Example:
[Link](-1) is the same as [Link]().
[Link](1) is the same as [Link](). 79
JavaScript Objects and Events…
2.6 Number Object
• The Number object contains some information and power of value to
serious programmers.
• The Number.MAX_VALUE and Number.MIN_VALUE properties belong to
the static Number object.
• They represent constants for the largest and smallest possible positive
numbers that JavaScript can work with.
• Their actual values are 1.7976931348623157 * 10308, and 5 * 10-324,
respectively.

• A number that falls outside the range of allowable numbers is equal to


the constant Number.POSITIVE_INFINITY or 80
JavaScript Objects and Events…
Properties Methods
MAX_VALUE toExponential()
MIN_VALUE toFixed()
NaN toLocaleString()
NEGATIVE_INFINITY toString()
POSITIVE_INFINITY toPrecision()
valueOf()

 The toExponential() method forces a number to display in exponential


notation.
 The parameter is an integer specifying how many digits to the right of the
81
JavaScript Objects and Events…
• Example:
var num = 345;
num=[Link](3);
alert(num); //3.450e+2 which means 3.45 × 102
• Use the toFixed() method when you want to format a number with a
specific number of digits to the right of the decimal.
• This is the method you use, for instance, to display the results of a
financial calculation.
• If the number being formatted has more numbers to the right of the
decimal, the method rounds the rightmost visible digit.
• Example:
var num = 123.455;
num=[Link](2);
alert(num); //123.46

82
JavaScript Objects and Events…
• The final method is toPrecision(), which enables you to define how many total digits to
display of a number.
• In other words, you define the precision of a number.
• This includes digits to the left and right of the decimal

• Example:
var num = 123.45
[Link](1); // result = 1e+2
[Link](2) ; // result = 1.2e+2
[Link](3) ; // result = 123
[Link](4) ; // result = 123.5
[Link](5) ; // result = 123.45
[Link](6) ; // result = 123.450
83
JavaScript Objects and Events…
3.2.7 Window Object
• At the very top of the document object hierarchy is the window object.
• It is the master container for all content you view in the Web browser.

• Methods:
• [Link]() - this method opens a new window. The syntax is:
[Link](“URL”, “name” [, “windowfeatures”]);

• Parameters:
• URL is a string that points to the window you want to open.
• name is a string that names the new window.
84
JavaScript Objects and Events…
• name is a string that names the new window.
• windowfeatures is one or more of the following in a comma-separated list:
• toolbar - toolbar is present. The value is yes or no.
• location – Location bar is present. The value is yes or no.
• directories
• status – statusbar is present. The value is yes or no.
• menubar – menubar is present. The value is yes or no.
• scrollbars – scrollbars are present. The value is yes or no.
• resizable – window is resizable. The value is yes or no.
• copyhistory
• width – width of the window
• height – height of the window
[Link](“[Link]”, “testing ”, “toolbar=yes,status=yes”);

85
JavaScript Objects and Events…
• In a more controlled way using windowfeatures:
newWin=[Link]("", "New", "height=250, width=250,
toolbar=no, scrollbars=yes, menubar=no");
[Link]("<TITLE>Title Goes Here</TITLE>");
[Link]("<BODY BGCOLOR=pink>");
[Link]("<h1>Hello!</h1>");
[Link]("This text will appear in the window!");
[Link]("</BODY>");
[Link]("</HTML>");
[Link]();
86
Method Description
[Link](message) Displays an alert dialog.
[Link]() Moves back one in the window history.
[Link]() Sets focus away from the window.
[Link](([Link]) Registers the window to capture all specified events.
[Link](intervalID) Clears a delay that’s been set for a specific function.
[Link](timeoutID) Clears the delay set by [Link]().
[Link]() Closes the current window.
[Link](message) Displays a dialog with a message that the user needs to
respond to.
[Link](message) Writes a message to the console.
[Link](text) Encodes a string.
[Link]() Sets focus on the current window.
[Link]() Moves the window one document forward in the history.
[Link]() Flashes the application icon to get user attention.
[Link]() Returns the selection object representing the selected
item(s).
[Link]() Returns the browser to the home page.
[Link](pixelX, pixelY) Moves the current window by a specified amount.

87
[Link](x, y) Moves the window to the specified coordinates.
[Link](URL,name[,features]) Opens a new window.
[Link]() Prints the current document.
[Link](message[,default]) Returns the text entered by the user in a prompt dialog.
[Link]([Link]) Releases the window from trapping events of a specific type.

[Link](pixelX, pixelY) Resizes the current window by a certain amount.


[Link](iWidth, iHeight) Dynamically resizes window.

[Link](x-coord, y-coord) Scrolls the window to a particular place in the document.


[Link](pixelX, pixelY) Scrolls the document in the window by the given amount.
[Link](lines) Scrolls the document by the given number of lines.
[Link](pages) Scrolls the current document by the specified number of
pages.
[Link](x-coord, y-coord) Scrolls to a particular set of coordinates in the document.
[Link](cursortype) Changes the cursor.
[Link](“funcName”, delay) Set a delay for a specific function.

[Link](“funcName”, delay) Sets a delay for executing a function.


88
JavaScript Objects and Events…
• Some of the properties of Window object are:
• [Link]- Gets/sets the name of the window.
• [Link]- Gets/sets the location, or current URL, of the window object.
• [Link] - Gets/sets the text in the statusbar at the bottom of the browser.
• [Link] - Returns the statusbar object, whose visibility can be toggled in the window.
• [Link]- Returns the toolbar object, whose visibility can be toggled in the window.
• [Link]- Returns the menubar object, whose visibility can be toggled in the window.
• [Link]- Returns the number of frames in the window.

89
<html>
<head>
<title>Show Title</title>
<script language="JavaScript">
var t = setInterval("showTime()",100);
function showTime()
{
var dt = new Date();
var hr = [Link]();
var min = [Link]();
var sec = [Link]();
if(min < 10) //append 0 if minutes < 10
min = "0" + min;
if(sec < 10) //append 0 if seconds < 10
sec = "0" + sec;
[Link] = hr + ":" + min + ":" + sec;
}
</script>
</head>
<body>
<form name="display">
<input type="text" name="time">
</form>
</body>
</html> 90
JavaScript Objects and Events…
3.2.7 Image Object
• The Image object reflects the attributes of an image on the current page.
• An image on the page can be referred to either via the images[] array or
by the image name, as shown here:
[Link][2].propertyName
[Link]

• Properties
• border - Reflects the BORDER attribute
• complete - Boolean value indicating whether Navigator has
completed its attempt to load the image
• height - Reflects the HEIGHT attribute.
• hspace - Reflects the HSPACE attribute.
• lowsrc - Reflects the LOWSRC attribute.
• name - Reflects the NAME attribute. 91
JavaScript Objects and Events…
• Properties…
• Prototype - Lets you add properties to an Image object.
• src - Reflects the SRC attribute (can dynamically change
the image on a page).
• vspace - Reflects the VSPACE attribute.
• width - Reflects the WIDTH attribute.

• The images[] array also contains this property:


• length - Reflects how many images are in the page (e.g.
[Link]).

92
Example: image slide show using JavaScript
<html>
<head>
<script language="JavaScript">
photonames = new Array('[Link]', '[Link]', 'Ethiopia_regions.png',
‘[Link]', '[Link]');
var tt = setInterval("slideshow()", 2000);
currentphoto = 0;
function slideshow()
{
currentphoto++;
if(currentphoto > [Link] - 1)
currentphoto = 0;
[Link] = photonames[currentphoto];
}
</script>
</head>
<body>
<img src="[Link]" id="photo" height="80%"> <br>
</body> 93
Form Processing and Validation
• It is possible to access form and form elements from
JavaScript.
• You can set attributes for NAME, TARGET, ACTION, METHOD,
and ENCTYPE for form.
• Each of these is a property of a FORM object, accessed by all
lowercase versions of those words, as in:
[Link][0].action //forms array of the document
[Link] //references exact form by
name

• To change any of these properties, simply assign new values to


them:
[Link] = “[Link]
94
Form Processing and
Validation…
• Forms support different events:
• onFocus -- an event is triggered with a form object gets input focus.
• onBlur – this event is triggered when a form object loses input focus.
• onChange – an event is triggered when a new item is selected in a
list box.
• This event is also trigged with a text or text area box loses focus and
the contents of the box has changed.
• onSelect – an event is triggered when text in a text or text area box
is selected.
• onSubmit – an event is triggered when the form is submitted to the
server. 95
Form Processing and
Validation…
Text boxes and Text areas
• Text fields have a value property.
• The value property of the input text box, is both readable and
writable.
• To access text input fields, you can use the syntax:
value = [Link]; //read content
[Link] = value; //set content

• Text box and textarea properties:


• name - String value of the NAME attribute.
• value - String value of the contents of the field.
• defaultValue - String value of the initial contents of the field.
• type - Specifies what type of object this form field is (e.g. “text” or 96
Form Processing and
Validation…
Methods
• focus( ) - Sets input focus to the object.
• blur( ) - Removes input focus from the object.
• select( ) - Selects the object's input field.

Event Handlers
• onFocus - executed when input focus enters field (by tabbing in or by
clicking but not selecting in the field).
• onBlur - executed when input focus leaves the field.
• onSelect - executed when the field is input-focused by selecting some of
its text.
• onChange - executed when input focus exits the field and the value of the
field has changed from when onFocus occurred.

• Text area has the same property as text field: the value property. Using 97
<HTML>
<HEAD>
<TITLE>JavaScript Form Input</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function add()
{
var op1 = [Link];
var op2 = [Link];
var sum = op1 + op2;
[Link] = sum;
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="test" ACTION="" METHOD="GET">
First number: <INPUT TYPE="text" NAME="fnum"><br>
Second number: <INPUT TYPE="text" NAME="snum"><br>
Result: <INPUT TYPE="text" NAME="result"><br>
<INPUT TYPE="button" NAME="adder" Value="Add" onClick="add()">
</FORM>
</BODY> 98
Form Processing and
Validation…
Checkboxes and Radio Buttons
• To define radio buttons for JavaScript, provide each object with the same
name.
• JavaScript will create an array using the name you've provided; you then
reference the buttons using the array indexes.
• Use the checked property to know the state of the individual radio
buttons.

• Radio button has the following properties:


• name - String value of the NAME attribute.
• length - The number of radio buttons in the radio object.
• Value - String value of the VALUE attribute.
• Checked - Boolean value which is true if pressed and false if not pressed.
• defaultChecked - Boolean property that reflects the value of the CHECKED
attribute. 99
<HTML>
<HEAD>
<TITLE>Test Input</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function hello () {
var urname = [Link];
var sex;
if([Link][0].checked)
sex = [Link][0].value;
else if([Link][1].checked)
sex = [Link][1].value;
alert ("Hello, " + urname + "! Your are "+sex);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="test" ACTION="" METHOD="GET">
Enter your name: <INPUT TYPE="text" NAME="name" VALUE=""><br>
Sex: <INPUT TYPE="radio" NAME="sex" Value="Male">Male<BR>
<INPUT TYPE="radio" NAME="sex" Value="Female">Female<BR>
<INPUT TYPE="button" NAME="button" Value="Say Hello" onClick="hello()">
</FORM>
100
</BODY>
Form Processing and
Validation…
Using Selection Lists
• Use the selectedIndex property to test which option item is
selected in the list.
• The item is returned as an index value, with 0 being the first option,
1 being the second, and so forth.
• If no item is selected, the value is -1.
• Select has the following properties in JavaScript:
• length - Contains the number of objects in the select object.
• name - The internal name of the select object as defined by the
NAME attribute.
• selectedIndex - The index number of the currently selected option of
the select object.

101
Form Processing and
Validation…
• options[] - This property is an object reflecting the contents of the
<OPTION> tag used when defining a select object in HTML.
• It contains the following properties:
• text - String containing the text after the <OPTION> tag. Assigning a new
value to options[index].text will either change the menu item text or add
a new item, in the case of an index higher than the current number of
items.
• Value - Reflection of the VALUE attribute. This is sent to the server when
the Submit button is pressed.
• defaultSelected - Boolean that reflects the SELECTED attribute of the
<OPTION> tag.
• selected - Boolean that indicates the current selected state of the option.
• Event handlers:
• onFocus - executed when input focus enters the field.
• onBlur - executed when input focus leaves the field.
• onChange - executed when input focus exits the field and the field value
102
has changed since the focus event
</SCRIPT>
<HTML>
<HEAD> </HEAD>
<TITLE>List Box Test</TITLE> <BODY>
<SCRIPT LANGUAGE="JavaScript"> <FORM NAME=“test" ACTION="[Link]"
function testSelect () { METHOD="GET">
var Item = Fruit: <SELECT NAME="list" SIZE="1">
[Link]; <OPTION>none</OPTION>
result = <OPTION>Orange</OPTION>
[Link][Item].text <OPTION>Apple</OPTION>
;
<OPTION>Papaya</OPTION>
//Or you can use the following line
which does the same as the above <OPTION>Banana</OPTION>
line </SELECT>
result = [Link]; <INPUT TYPE="button" NAME="button"
alert (result); value="Test" onClick="testSelect()">
} </FORM>
</BODY>
</HTML>

103
Form Processing and
Validation…

THE END

104
Thank you!!

105

You might also like