0% found this document useful (0 votes)
2 views32 pages

UNIT-II - JavaScript

Uploaded by

Jaya Raju
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)
2 views32 pages

UNIT-II - JavaScript

Uploaded by

Jaya Raju
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

CSE IV-I : R16 UNIT-II JavaScript & DHTML

UNIT-2
JavaScript and DHTML

JavaScript, which was developed by Netscape, was originally named Mocha but soon was renamed
LiveScript. In late 1995 LiveScript became a joint venture of Netscape and Sun Microsystems, and its
name again was changed JavaScript can be divided into three parts: the core, client side, and server
side. The core is the heart of the language, including its operators, expressions, statements, and
subprograms. Client-side JavaScript is a collection of objects that support the control of a browser
and interactions with users.
As stated previously, JavaScript is not an object-oriented programming language. Rather, it is an
object-based language. JavaScript does not have classes. Its objects serve both as objects and as
models of objects. Without classes, JavaScript cannot have class-based inheritance, which is
supported in object-oriented languages such as C++ and Java

JavaScript Objects
• In JavaScript, objects are collections of properties.
• Each property is either a data property or a function or method property.
• Data properties appear in two categories: primitive values and references to other objects.
Sometimes we will refer to the data properties simply as properties; we often refer to the method
properties simply as methods or functions
• All objects in a JavaScript program are indirectly accessed through variables. Such a variable is
like a reference in Java. All primitive values in JavaScript are accessed directly—these are like
the scalar types in Java and C++.
• Primitive values are often implemented directly in hardware.
• The properties of an object are referenced by attaching the name of the property to the variable
that references the object. For example, if myCar is a variable referencing an object that has the
property engine, the engine property can be referenced with [Link].
• The root object in JavaScript is Object. It is the ancestor, through prototype inheritance, of all
objects. Object is the most generic of all objects, having some methods but no data properties.
• A JavaScript object appears, both internally and externally, as a list of property–value pairs.
• The properties are names; the values are data values or functions.
• All functions are objects and are referenced through variables. The collection of properties of a
JavaScript object is dynamic: Properties can be added or deleted at any time.
The Syntax (General format) is
<script [Attributes = [Value] . ]>
… Javascript here …
</script>
JS code can be directly embedded in HTML document = placed in-line up to </script> closing tag
<script type=“text/javascript”>
<!--
… Javascript here …
1
CSE IV-I : R16 UNIT-II JavaScript & DHTML

//-->
</script>

JS code can be indirectly embedded in HTML document = URL of a JS code file can be added as a
src= attribute
<script type=“text/javascript” src=“tst_number.js”></script>
General Syntactic Characteristics
Identifiers
• Start with $, _, letter
• Continue with $, _, letter or digit
• Case sensitive
Statement Syntax
• Statements can be terminated with a semicolon
• However, the interpreter will insert the semicolon if missing at the end of a line and the
statement seems to be complete
• Can be a problem:
return
x;
• If a statement must be continued to a new line, make sure that the first line does not make a
complete statement by itself

Primitives, Operations, and Expressions


Primitive Types
JavaScript has five primitive types: Number, String, Boolean, Undefined, and Null. Each primitive
value has one of these types.
JS also includes predefined wrapper objects Number, String, and Boolean;
 each contains only a property that stores a value of the corresponding primitive type
 each provides useful methods to use with values of corresponding primitive type
 JS converts automatically between primitive types and corresponding wrapper objects
→ methods of String object can be directly used on a variable storing a primitive
string value

Primitive and Object Storage

2
CSE IV-I : R16 UNIT-II JavaScript & DHTML

1. Number Type: Number values are represented internally as double-precision floating-point


values.
Number literals can be either integer or float
Float values may have a decimal and/or and exponent
Some examples of numbers are: 29, -43, 3.40, 3.4323
E g: var num_val=5;
Conversions:
Number(…), parseInt(…) and parseFloat(…) functions turn strings into numbers
2. String Type: A string is a collection of letters, digits, punctuation characters, and so on. A
string literal is enclosed within single quotes or double quotes (or ). Examples of string literals
are: welcome, 7.86 , wouldnt you exit now, country=India
Eg: var str_val= ‘java script’; var str_val2= “java script”;
No difference between single quote and double quote, but end quote must match start quote.
It can include escaped characters as in Java
E.g. \n, \”, \\, etc.
[Link] (“Abhinav said, \”Earth doesn\’t revolve round ↵ the sun\”. But teacher
corrected him.”);
Conversions
toString() method of Number object turns numbers into strings
E.g: var num = 5; var str=[Link]()//Explicit conversion
other implicit conversions
JS attempts to convert to a string the non-string operator in a string concatenation operation;
ex. “August” + 1977
+ sign is string concatenation operator (as in Java) if either side is a string
3. Boolean Type: A boolean variable can store only two possible values either true or false.
Internally it is stored as 1 for true and 0 for false. It is used to get the output of conditions,
whether a condition results in true or false.
Example: x == 100; // results true if x=100 otherwise false
 These are reserved words
 Note – not “true” or “false” (strings)
Conversions
 When boolean converted to string, get “true” or “false”
 Empty string is considered false, all others true
 Number 0 is considered false, all others true
 Undefined, NaN and null are considered false
4. null
 JavaScript supports a special data type known as null that indicates no value or blank.
Note that null is not equal to 0.
 Using a null value usually causes a runtime error
Example: var distance = new object(); distance = null
5. undefined
 It is a single value, undefined; however undefined is not a keyword

3
CSE IV-I : R16 UNIT-II JavaScript & DHTML

 Is the value of a variable declared but not initialized


 Remains undefined until a value is assigned
Example: var value; var value=undefined;

Type Conversions:
Implicit Type Conversion
• JavaScript attempts to convert values in order to be able to perform operations
• “August “ + 1977 causes the number to be converted to string and a concatenation to be
performed
• 7 * “3” causes the string to be converted to a number and a multiplication to be performed
• null is converted to 0 in a numeric context, undefined to NaN
• 0 is interpreted as a Boolean false, all other numbers are interpreted a true
• The empty string is interpreted as a Boolean false, all other strings (including “0”!) as
Boolean true
• undefined, Nan and null are all interpreted as Boolean false
Explicit Type Conversion
• Explicit conversion of string to number
• Number(aString)
• aString – 0
• Number must begin the string and be followed by space or end of string
• parseInt and parseFloat convert the beginning of a string but do not cause an error if a non-
space follows the numeric part

Number object
The Number object includes a collection of useful properties that have constant value. These
properties are referenced through Number. For example:var num = Number.MIN_VALUE;
• Properties
• MAX_VALUE
• MIN_VALUE
• NaN
• POSITIVE_INFINITY
• NEGATIVE_INFINITY
• PI
Any arithmetic operation that results in an error (e.g., division by zero) or that produces a value
that cannot be represented as a double-precision floating-point number, such as a number that is too
large (an overflow), returns the value “not a number,” which is displayed as NaN
The Number object has a method, toString, which it inherits from Object but overrides. The
toString method converts the number through which it is called to a string.
var price = 427,
str_price;

4
CSE IV-I : R16 UNIT-II JavaScript & DHTML

...
str_price = [Link]();

String object
The String object includes one property, length, and a large collection of methods. String methods
can always be used through String primitive values, as if the values were objects.

The number of characters in a string is stored in the length property as follows:

var str = “George”; var len = [Link]// number of characters is 6.

In the expression [Link], str is a primitive variable, but we treated it as if it were an object
(referencing one of its properties). In fact, when str is used with the length property, JavaScript
implicitly builds a temporary String object with a property whose value is that of the primitive
variable. After the second statement is executed, the temporary String object is discarded.

Belong to String object, but JS automatically converts primitive string values to wrapper objects →
can be used through string primitive values directly.
A few of the most commonly used String methods are as follows:
Method Parameters Result

charAt A number Returns the character in the String


object that is at the specified position

indexOf One-character Returns the position in the String


string object of the parameter

substring Two numbers Returns the substring of the String


object from the first parameter
position to the second

toLowerCase None Converts any uppercase letters in the


string to lowercase

toUpperCase None Converts any lowercase letters in the


string to uppercase
Examples:
“George”.charAt(2) returns ‘o’
Given integer argument, returns one character (as string)
Note character positions in strings begin at index 0
indexOf( ): “George”.indexOf(‘r’) returns 3
Given one search string, returns its index or -1
substring( ): “George”.substring(2, 4) returns ‘org’
Given start and end indexes, returns string

5
CSE IV-I : R16 UNIT-II JavaScript & DHTML

toLowerCase( ): “George”.toLowerCase() returns ‘george’


toUpperCase( ): “George”.toLowerCase() returns ‘GEORGE’

Date Object
• This object is used to set and manipulate date and time. A Date object represents a time stamp,
that is, a point in time
• A Date object is created with the new operator
• var now= new Date();
• This creates a Date object for the time at which it was created
Methods to get date values
We can use the get methods to get values from a Date object. Here are some get methods that returns
some value according to local time:

toLocaleString A string of the Date information

getDate The day of the month

getMonth The month of the year, as a number in the range of 0 to 11

getDay The day of the week, as a number in the range of 0 to 6

getFullYear The year

getTime The number of milliseconds since January 1, 1970

getHours The number of the hour, as a number in the range of 0 to 23

getMinutes The number of the minute, as a number in the range of 0 to 59

getSeconds The number of the second, as a number in the range of 0 to 59

getMilliseconds The number of the millisecond, as a number in the range of 0 to 999

Math Object

This object contains methods and constants to carry more complex mathematical operations. This
object cannot be instantiated like other objects. All properties and methods of Math are static. We can

6
CSE IV-I : R16 UNIT-II JavaScript & DHTML

refer to the constant p as [Link] and the sine function as [Link](x), where x is the methods
argument.

Properties Description

[Link] Returns the value of p

Math.E Eulers constant and the base of natural logarithms.

Methods Description

pow(x, p) Returns XP
abs(x) Returns absolute value of x.
exp(x) Returns ex
log(x) Returns the natural logarithm of x.
sqrt(x) Returns the square root of x.
random() Returns a random number between 0 and 1.
ceil(x) Returns the smallest integer greater than or equal to x.
floor(x) Returns the largest integer less than or equal to x.
min(x, y) Returns the lesser of x and y.
max(x, y) Returns the larger of x and y.
round(x) Rounds x up or down to the nearest integer.
sin(x) Returns the sin of x, where x is in radians.
cos(x) Returns the cosine of x, where x is in radians.
tan(x) Returns the tan of x, where x is in radians.

EXPRESSIONS AND OPERATORS


An expression is a combination of operators operands that can be evaluated. It may also include
function calls which return values.

ARITHMETIC OPERATORS: These are used to perform arithmetic/mathematical operations like


subtraction, division, multiplication etc. Arithmetic operators work on one or more numerical values
(either literals or variables) and return a single numerical value. The basic arithmetic operators are:
+ (Addition) - (Subtraction) * (Multiplication)

/ (Division) % (Modulus) ++ (Increment by 1) --(Decrement by 1)

Examples
var s = 10 + 20; // result: s=30
var h = 50 * 4; // result: h = 20
var d = 100 / 4; // result: d = 25
var r = 72 % 14; // result: r=2

7
CSE IV-I : R16 UNIT-II JavaScript & DHTML

INCREMENT AND DECREMENT OPERATORS: These operators are used for increasing or
decreasing the value of a variable by 1. Calculations performed using these operators are very fast.
Example
var a = 15; a++; // result: a = 15 var b = 15; ++b; // result: b = 16
var a = 15; a--; // result: a = 15 var b = 15; --b; // result: b = 14

ASSIGNMENT OPERATORS
It assigns the value of its right operand to its left operand. This operator is represented by equal
sign(=).
Example x = 100; // This statement assigns the value 100 to x.
JavaScript also supports shorthand operator for standard operations(Compound assignment)
Shorthand operator Example is equivalent to
+= a+=b a=a+b
-= a- = b a=a- b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b

RELATIONAL (COMPARISON) OPERATORS


Relational Operators are some symbols which return a Boolean value true or false after evaluating the
condition. For example x > y; returns a value true is value of variable x is greater than variable y.

Operator Description Example


== is equal to 4 = = 8 returns false
!= is not equal to 4 ! = 8 returns true
> is greater than 8 > 4 returns true
< is less than 8 > 4 returns false
<= is less than or equal to 8 < = 4 returns false
>= is greater than or equal to 8 > = 4 returns true

LOGICAL OPERATORS
Logical operators are used for combining two or more conditions. JavaScript has following three
logical operators
Operator Description with Example
&& (AND) returns true if both operands are true else it return false.
| | (OR) returns false if both operands are false else it returns true.
! (NOT) returns true if the operand is false and false if operand is true

8
CSE IV-I : R16 UNIT-II JavaScript & DHTML

CONCATENATION OPERATOR
The + operator concatenates two string operands. The + operator gives priority to string operands
over numeric operands It works from left to right. The results depend on the order in which
operations are performed. For example :
Statement Output
“Good” + “Morning” “GoodMorning”
“5” + “10” “ 510”
“Lucky” + 7 “Lucky7”
“4 + 7 + “Delhi” “11Delhi”
“Mumbai” + 0 +0+ 7 “Mumbai007”

Conditional Operator ( ? : )
The conditional operator is a special JavaScript operator that takes three operands. Hence, it is also
called ternary operator. A conditional operator assigns a value to a variable based on the condition.
var_name = (condition) ? v_1 : v_2
If (condition) is true, the value v_1 is assigned to the variable, otherwise, it assigns the value v_2 to
the variable.
For example
status = (age >= 18) ? “adult” : “minor”
This statement assigns the value adult to the variable status if age is eighteen or more. Otherwise, it
assigns the value minor to status.
The typeof operator
The typeof operator returns the type of its single operand. typeof produces “number”, “string”, or
“boolean” if the operand is of primitive type Number, String, or Boolean, respectively. If the operand
is an object or null, typeof produces “object”. If the operand is a variable that has not been assigned a
value, typeof produces “undefined”. The operand for typeof can be placed in parentheses, making it
appear to be a function. Therefore, typeof x and typeof(x) are equivalent.

Screen Output and Keyboard Input


• Standard output for JavaScript embedded in a browser is the window displaying the page in
which the JavaScript is embedded
• The write method of the Document object write its parameters to the browser window
• The output is interpreted as HTML by the browser
• If a line break is needed in the output, interpolate <br/> into the output
• The Window object represents the window in which the document containing the script is
being displayed
• The Document object represents the document being displayed using DOM
• The Window object includes two properties, document and window.
• The document property refers to the Document object.
• The window property is self-referential; it refers to the Window object.
• The Document object has several properties and methods.

9
CSE IV-I : R16 UNIT-II JavaScript & DHTML

• The most interesting and useful of its methods, at least for now, is write, which is used to
create script output, which is dynamically created HTML document content.
For example, if the value of the variable result is 42, the following statement produces the screen
var result=[Link](“The result is: ” +result);

• The Window object is the default object for JavaScript, so properties and methods of the
Window object may be used without qualifying with the class name

The alert method


• The alert method opens a dialog box with a message. The output of the alert is not HTML, so
use new lines rather than <br/>/
As an example of an alert, consider the following code, in which we assume that the value of result is
42.
alert("The result is:" + result + “\n”);

The confirm Method


The confirm methods displays a message provided as a parameter. The confirm dialog has two
buttons: OK and Cancel. If the user presses OK, true is returned by the method. If the user presses
Cancel, false is returned
var question = confirm(“Do you want to continue this download?”);

10
CSE IV-I : R16 UNIT-II JavaScript & DHTML

The prompt Method


Prompt box allows getting input from the user. This method displays its string argument in a
dialog box A second argument provides a default content for the user entry area. The dialog box has
an area for the user to enter text. The method returns a String with the text entered by the user

var name = prompt("What is your name?", "");

alert, prompt, and confirm cause the browser to wait for a user response. In the case of alert, the OK
button must be pressed for the Java-Script interpreter to continue. The prompt and confirm methods
wait for either OK or Cancel to be pressed

Control Statements
Control statements control the order of execution in a program, based on data values and conditional
logic. Control statements frequently require some syntactic container for sequences of statements
whose execution they are meant to control. In JavaScript, that container is the compound statement
• A compound statement in JavaScript is a sequence of 0 or more statements enclosed in curly
braces
• Compound statements can be used as components of control statements allowing multiple
statements to be used where, syntactically, a single statement is specified
• A control construct is a control statement including the statements or compound statements
that it contains

Control Expressions
• A control expression has a Boolean value
• An expression with a non-Boolean value used in a control statement will have its value
converted to Boolean automatically
• If the two operands are not of the same type and the operator is neither = = = nor != =,
JavaScript will attempt to convert the operands to a single type. In the case in which
one operand is a string and the other is a number, JavaScript attempts to convert the
string to a number. If one operand is Boolean and the other is not, the Boolean value is
converted to a number (1 for true, 0 for false).
• If a and b reference different objects, a == b is never true, even if the objects have
identical properties. a == b is true only if a and b reference the same object.

11
CSE IV-I : R16 UNIT-II JavaScript & DHTML

• Comparison operators
• == != < <= > >=
• = = = compares identity of values or objects
• 3 = = ‘3’ is true due to automatic conversion
• 3 = = = ‘3’ evaluates to false
• Boolean operators
• && || !
• Precedence of Operators
Highest-precedence operators are listed first.

Operators Associativity

++, --, unary - Right

*, /, % Left

+, - Left

>, <, >= ,<= Left

==, != Left

===,!== Left

&& Left

|| Left

=, +=, -=, *=, /=, &&=, ||=, %= Right

Example:
var a = 2,
b = 4,
c,
d;
c = 3 + a * b;
// * is first, so c is now 11 (not 24)
d = b / a / 2;
// / associates left, so d is now 1 (not 4)

12
CSE IV-I : R16 UNIT-II JavaScript & DHTML

Selection Statements
The selection statements (if-then and if-then-else) of JavaScript are similar to those of the common
programming languages. Either single statements or compound statements can be selected—for
example,

if (a>b)
[Link](“a is greater than b <br />”);
else {
a=b;
[Link](“a is not greater than b <br />”, “now they are equal <br />” );
}

The switch Statement


JavaScript has a switch statement that is similar to that of Java. The form of this construct is as
follows:

switch (expression) {
case value_1:
// statement(s)
case value_2:
// statement(s)
...
[default:
// statement(s)]
}
 The expression is evaluated
 The value of the expressions is compared to the value in each case in turn
 If no case matches, execution begins at the default case
 Otherwise, execution continues with the statement following the case
 Execution continues until either the end of the switch is encountered or a break statement
is executed

Loop Statements
Loop statements in JavaScript are similar to those in C/C++/Java

 While
Syntax: while (control expression)
statement or compound statement

 The control expression is evaluated


 If the control expression is true, then the statement is executed
 These two steps are repeated until the control expression becomes false

13
CSE IV-I : R16 UNIT-II JavaScript & DHTML

 At that point the while statement is finished

 For
Syntax : for (initial expression; control expression; increment expression)
statement or compound statement

 The initial expression is evaluated


 The control expression is evaluated
 If the control expression is true, the statement is executed
 Then the increment expression is evaluated
 The previous three steps are repeated as long as the control expression remains true
 When the control expression becomes false, the statement is finished executing

 do-while
Syntax: do statement or compound statement
while (control expression)

 The statement is executed


 The control expression is evaluated
 If the control expression is true, the previous steps are repeated
 This continues until the control expression becomes false
 At that point, the statement execution is finished

Object Creation and Modification


• The new operator is used to create an object
• This includes a call to a constructor
• The new operator creates a blank object, that is, one with no properties. Furthermore,
JavaScript objects do not have types
• The constructor creates and initializes all properties of the object
The following statement creates an object that has no properties
var my_object = new Object();
In this case, the constructor called is that of Object, which provides the new object with no properties,
although it does have access to some inherited methods. The variable my_object references the new
object. Calls to constructors must include parentheses, even if there are no parameters.
• Properties of an object are accessed using a dot notation: [Link]
• in which the first word is the object name and the second is the property name. Properties are
not actually variables—they are just the names of values. They are used with object variables
to access property values. Because properties are not variables, they are never declared.
• The number of members of a class in a typical object-oriented language is fixed at compile
time
• The number of properties of an object may vary dynamically in JavaScript

14
CSE IV-I : R16 UNIT-II JavaScript & DHTML

• At any time during interpretation, properties can be added to or deleted from an object. A
property for an object is created by assigning a value to that property’s name. Consider the
following example:
Create my_car and add some properties
// Create an Object object
var my_car = new Object();
// Create and initialize the make property
my_car.make = "Ford";
// Create and initialize model
my_car.model = "Contour SVT";

This code creates a new object, my_car, with two properties: make and model. There is an
abbreviated way to create an object and its properties.
For example, the object referenced with my_car in the previous example could be created with the
following statement:
var my_car = {make: “Ford”, model: “Contour SVT”};
this statement includes neither the new operator nor the call to the Object constructor. Because
objects can be nested, you can create a new object that is a property of my_car with properties of its
own, as in the following statements:

my_car.engine = new Object();


my_car.[Link] = "V6";
my_car.[Link] = 200;
Properties can be accessed in two ways.
var prop1 = my_car.make;
var prop2 = my_car[“make”];
• The delete operator can be used to delete a property from an object
delete my_car.model.

The for-in Loop


JavaScript has a loop statement, for-in, that is perfect for listing the properties of an object. The form
of for-in is:

Syntax : for (identifier in object)


statement or compound statement

• The loop lets the identifier take on each property in turn in the object
• Printing the properties in my_car:
for (var prop in my_car)
[Link]("Name: ", prop, "; Value: ",my_car[prop], "<br />");
• Result:
Name: make; Value: Ford
15
CSE IV-I : R16 UNIT-II JavaScript & DHTML

Name: model; Value: Contour SVT

Arrays
 Arrays are lists of elements indexed by a numerical value
 Array indexes in JavaScript begin at 0
 Arrays can be modified in size even after they have been created
 In JavaScript, arrays are objects that have some special functionality.
 Array elements can be primitive values or references to other objects, including other arrays.
 JavaScript arrays have dynamic lengths.

Array Object Creation


Array objects, unlike most other JavaScript objects, can be created in two distinct ways. The usual
way to create any object is with the new operator and a call to a constructor. In the case of arrays, the
constructor is named Array:
var my_list = new Array(1, 2, “three”, “four”);

new Array with one parameter creates an empty array of the specified number of elements
var your_list=new Arrary(100);
new Array with two or more parameters creates an array with the specified parameters as elements
var your_list =new Array(10, 20);
The second way to create an Array object is with a literal array value, which is a list of values
enclosed in brackets
Literal arrays can be specified using square brackets to include a list of elements
var alist = [1, “ii”, “gamma”, “4”];
Elements of an array do not have to be of the same type

Characteristics of Array Objects


• The length of an array is one more than the highest index to which a value has been assigned
or the initial size (using Array with one argument), whichever is larger
• Assignment to an index greater than or equal to the current length simply increases the length
of the array
• Only assigned elements of an array occupy space
• Suppose an array were created using new Array(200)
• Suppose only elements 150 through 174 were assigned values
• Only the 25 assigned elements would be allocated storage, the other 175 would not be
allocated storage
Array Methods
Array objects have a collection of useful methods. They are join, reverse, sort, concat, slice

join: The join method converts all of the elements of an array to strings and catenates them into a
single string. If no parameter is provided to join, the values in the new string are separated by
16
CSE IV-I : R16 UNIT-II JavaScript & DHTML

commas. If a string parameter is provided, it is used as the element separator. Consider the following
example
var names = new Arrary[“Mary”, “Max”, “Murphy”, “Murray”];

Var names_string = [Link](“ : ”);
The value of name_string is now “Mary : Murray : Murphy : Max”.
reverse: The reverse method does what you would expect: It reverses the order of the elements of the
Array object through which it is called.

sort: The sort method coerces the elements of the array to become strings if they are not already
strings and sorts them alphabetically. For example, consider the following statement:

[Link]();

The value of names is now [“Mary”, “Max”, “Murphy”, “Murray”].

concat: The concat method catenates its actual parameters to the end of the Array object on which it
is called.

var names = new Arrary[“Mary”, “Max”, “Murphy”, “Murray”];



Var names_string = [Link](“Moo ”, “Meow”);

slice: The slice method does for arrays what the substring method does for strings, returning the part
of the Array object specified by its parameters, which are used as subscripts. The array returned has
the elements of the Array object through which it is called, from the first parameter up to, but not
including, the second parameter. For example, consider the following code

var list = [2, 4, 6, 8, 10];



var list2 = [Link](1,3);
The value of list2 is now [4,6]

If slice is given just one parameter, the array that is returned has all of the elements of the object,
starting with the specified index. In the code

Var list =[“bill”, “will”, “jill”, “dill”];



var listette = [Link](2);
the value of listte = is [“jill”, “dill”]

17
CSE IV-I : R16 UNIT-II JavaScript & DHTML

Dynamic List Operations


The push, pop, unshift, and shift methods of Array allow the easy implementation of stacks and
queues in arrays. The pop and push methods respectively remove and add an element to the high end
of an array, as in the following code
• Push: Add to the end
• Pop: Remove from the end
var list = [“Dasher”, “Dancer”, “Donner”, “Blitzen”];
var deer= [Link]();
[Link](“Blitzen”);
• Shift: Remove from the front
• Unshif: Add to the front

The shift and unshift methods respectively remove and add an element to the beginning of an
array. For example, assume that list is created as before, and consider the following code:

var deer = [Link](); // deer is now “Dasher” [Link](“Dasher”); // This puts “Dasher” back
on list

Two-dimensional Arrays
• A two-dimensional array in JavaScript is an array of arrays
• This need not even be rectangular shaped: different rows could have different length
• Example of nested_array.js two-dimensional arrays :
var nested_array = [ [2, 4, 6], [1, 3, 5], [10, 20, 30] ];
for (var row=0; row <= 2; row++) {
[Link](“Row ”, row, “: ”);
for (var col=0; col <= 2; col++) {
[Link](“nested_arrary[row][col], “ ”);
[Link](“<br />”);
}

Output: Row 0:2 4 6


Row 0:1 3 5
Row 0:10 20 30

18
CSE IV-I : R16 UNIT-II JavaScript & DHTML

Functions
 JavaScript functions are similar to those of other C-based languages, such as C and
C++.
 A JavaScript function is a block of code designed to perform a particular task.

Function definition syntax


 A function definition consist of a header followed by a compound statement, that describes
the actions of the function. This compound statement is called the body of the function.
 A function header consists of the reserved word function, the function’s name, and a
parenthesized list of parameters if there are any.
 The parentheses are required even if there are no parameters.

A function header: function function-name(optional-formal-parameters)


return statements:
 A return statement causes a function to cease execution and control to pass to the caller
 A return statement may include a value which is sent back to the caller
 This value may be used in an expression by the caller
 A return statement without a value implicitly returns undefined

Function call syntax


 Function name followed by parentheses and any actual parameters
 Function call may be used as an expression or part of an expression
 Functions must defined before use in the page header

Functions are Objects


JavaScript functions are objects, so variables that reference them can be treated as are other object
references, they can be passed as parameters, be assigned to other variables, and be the elements of an
array.

Example:

function fun() {
[Link]("This surely is fun! <br/>");
}
ref_fun = fun; // Now, ref_fun refers to the fun object
fun(); // A call to fun
ref_fun(); // Also a call to fun

Because JavaScript functions are objects, their references can be properties in other objects, in which
case they act as methods.

19
CSE IV-I : R16 UNIT-II JavaScript & DHTML

To ensure that the interpreter sees the definition of a function before it sees a call to the function—a
requirement in JavaScript—function definitions are placed in the head of an HTML document (either
explicitly or implicitly). Normally, but not always, calls to functions appear in the document body.

Local Variables
 “The scope of a variable is the range of statements over which it is visible”
 A variable not declared using var has global scope, visible throughout the page, even if used
inside a function definition
 A variable declared with var outside a function definition has global scope
 A variable declared with var inside a function definition has local scope, visible only inside
the function definition
 If a global variable has the same name, it is hidden inside the function definition

Parameters
• Parameters named in a function header are called formal parameters
• Parameters used in a function call are called actual parameters
• Parameters are passed by value
• For an object parameter, the reference is passed, so the function body can actually
change the object
• However, an assignment to the formal parameter will not change the actual parameter

Parameter Passing Example


function fun1(my_list) {
var list2 = new Array(1, 3, 5);
my_list[3] = 14;
...
my_list = list2;
...
}
...
var list = new Array(2, 4, 6, 8)
fun1(list);
• The first assignment changes list in the caller
• The second assignment has no effect on the list object in the caller
• Pass by reference can be simulated by passing an array containing the value
Parameter Checking
• JavaScript checks neither the type nor number of parameters in a function call
• Formal parameters have no type specified
• Extra actual parameters are ignored (however, see below)
• If there are fewer actual parameters than formal parameters, the extra formal
parameters remain undefined
• This is typical of scripting languages

20
CSE IV-I : R16 UNIT-II JavaScript & DHTML

• A property array named arguments holds all of the actual parameters, whether or not there are
more of them than there are formal parameters
• Example [Link] illustrates this
The sort Method, Revisited
• A parameter can be passed to the sort method to specify how to sort elements in an array
• The parameter is a function that takes two parameters
• The function returns a negative value to indicate the first parameter should come
before the second
• The function returns a positive value to indicate the first parameter should come after
the second
• The function returns 0 to indicate the first parameter and the second parameter are
equivalent as far as the ordering is concerned

Constructors
JavaScript constructors are special methods that create and initialize the properties of newly created
objects. Every new expression must include a call to a constructor whose name is the same as that of
the object being created.
Constructors are actually called by the new operator, which immediately precedes them in the new
expression.
 A constructor uses the keyword this in the body to reference the object being initialized
 Object methods are properties that refer to functions
 A function to be used as a method may use the keyword this to refer to the object for which
it is acting
 The this variable is used to construct and initialize the properties of the object.

For example, the constructor could be used as in the following statement:

my_car = new car(“Ford”, “Contour SVT”, “2000”);

function car(new_make, new_model, new_year) {


[Link] = new_make;
[Link] = new_model
[Link] = new_year;
}

function display_car() {
[Link](“Car make:” +[Link] + “<br />”);
[Link](“Car model:” +[Link]+ “<br />”);
[Link](“Car year:” +[Link] + “<br />”);
}
The following line must then be added to the car constructor:

21
CSE IV-I : R16 UNIT-II JavaScript & DHTML

[Link] = display_car;
Now the call my_car.display() will produce the following output:
car make: Ford
car model: Contour SVT
car year: 2000
[Link]
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function car(new_make, new_model, new_year) {
[Link] = new_make;
[Link] = new_model;
[Link] = new_year;
[Link] = display_car;
}
my_car = new car("Ford", "Contour SVT", 2000);

function display_car() {
[Link]("Car make:" +[Link] + "<br />");
[Link]("Car model:" +[Link]+ "<br />");
[Link]("Car year:" +[Link] + "<br />");
}
my_car.display();
</script>
</body>
</html>

Regular Expressions
• Regular expressions are used to specify patterns in strings
• JavaScript provides two methods to use regular expressions in pattern matching
• String methods
• RegExp objects (not covered in the text)
• A literal regular expression pattern is indicated by enclosing the pattern in slashes
• The search method returns the position of a match, if found, or -1 if no match was found
Example Using search
var str = "Rabbits are furry";
var position = [Link](/bits/);
if (position > 0)
[Link](" 'bits' appears in position", position, "<br />");

22
CSE IV-I : R16 UNIT-II JavaScript & DHTML

else
[Link](" 'bits' does not appear in str <br />");
• This uses a pattern that matches the string ‘bits’
• The output of this code is as follows:
'bits' appears in position 3

Characters and Character-Classes


The “normal” characters are those that are not metacharacters. Metacharacters are characters that
have special meanings in some contexts in patterns. The following are the pattern metacharacters:
\|()[]{}^$*+?.
• Metacharacters can themselves be matched by being immediately preceded by a backslash. A
period matches any character except newline. So, the following pattern matches “snowy”,
“snowe”, and “snowd”, among others:
/snow./
• To match a period in a string, the period must be preceded by a backslash in the pattern. For
example, the pattern /3\.4/ matches 3.4. The pattern / 3.4/ would match 3.4 and 374, among
others.
• A character class matches one of a specified set of characters
• [character set]
• List characters individually: [abcdef]
• Give a range of characters: [a-z]
• Find any of the alternatives separated with |: (x|y)
• If a circumflex character (^) is the first character in a class, it inverts the specified set. For
example, the following character class matches any character except the letters ‘a’, ‘e’, ‘i’,
‘o’, and ‘u’:
• [^aeiou]
• ^ at the beginning negates the class
Predefined character classes
Name Equivalent Pattern Matches

\d [0-9] A digit

\D [^0-9] Not a digit

\w [A-Za-z_0-9] A word character


(alphanumeric)

\W [^A-Za-z_0-9] Not a word character

\s [ \r\t\n\f] A whitespace character

\S [^ \r\t\n\f] Not a whitespace character

23
CSE IV-I : R16 UNIT-II JavaScript & DHTML

The following examples show patterns that use predefined character classes:

Repeated Matches
• A pattern can be repeated a fixed number of times by following it with a pair of curly braces
enclosing a count
• A pattern can be repeated by following it with one of the following special characters
• * : An asterisk means zero or more repetitions
• +: a plus sign means one or more repetitions
• ?: a question mark means one or none
• Examples
• the following pattern matches strings that begin with any number of x’s
(including zero), followed by one or more y’s, possibly followed by z:
/x*y+z?/
• The following pattern matches a string of one or more digits followed by a decimal
point and possibly more digits:
/\d+\.\d*/
• The following matches the identifiers (a letter, followed by zero or more letters, digits,
or underscores) in some programming languages
/[A-Za-z]\w*/
• /\(\d{3}\)\d{3}-\d{4}/ might represent a telephone number
• /[$_a-zA-Z][$_a-zA-Z0-9]*/ matches identifiers
• To repeat a pattern, a numeric quantifier, delimited by braces, is attached.
For example, the following pattern matches xyyyyz:
/xy{4}z//

Anchors
• Anchors in regular expressions match positions rather than characters
• Anchors are 0 width and may not take multiplicity modifiers
• Anchoring to the end of a string
• ^ at the beginning of a pattern matches the beginning of a string
• $ at the end of a pattern matches the end of a string
• The $ in /a$b/ matches a $ character
• Anchoring at a word boundary
• \b matches the position between a word character and a non-word character or the
beginning or the end of a string
• /\bthe\b/ will match ‘the’ but not ‘theatre’ and will also match ‘the’ in the string ‘one
of the best’

Pattern Modifiers
• Modifiers can be attached to patterns to change how they are used, thereby increasing their
flexibility. The modifiers are specified as letters just after the right delimiter of the pattern.

24
CSE IV-I : R16 UNIT-II JavaScript & DHTML

Syntax: /pattern/modifiers where "pattern" is the regular expression itself, and


"modifiers" are a series of characters indicating various options. The "modifiers" part is
optional.
• The i modifier is used to perform case-insensitive matching
For example, the pattern /Apple/i matches ‘APPLE’, ‘apple’, ‘APPle’, and any other
combination of uppercase and lowercase spellings of the word “apple.”
 The g modifier is used to perform a global match (find all matches rather than stopping
after the first match). To perform a global, case-insensitive search, use this modifier
together with the "i" modifier
Example: var str = "Is this all there is?"; var patt1 = /is/gi;
 The m i used to perform multiline matching
Example: var str = "\nIs th\nis it?"; var patt1 = /^is/m;
 The x modifier allows white space to appear in the pattern. Because comments are
considered white space, this provides a way to include explanatory comments in the
pattern.

Other Pattern Matching Methods


• The replace method takes a pattern parameter and a string parameter
The method replaces a match of the pattern in the target string with the second parameter
A g modifier on the pattern causes multiple replacements
Example: var str = "Visit Microsoft!";
var res = [Link]("Microsoft", "W3Schools"); output: "Visit W3Schools";
• The match method takes one pattern parameter
• Without a g modifier, the return is an array of the match and parameterized sub-
matches
• With a g modifier, the return is an array of all matches
Example: var str = "The rain in SPAIN stays mainly in the plain";
var res = [Link](/ain/g); output: ain,ain,ain
• The split method splits the object string using the pattern to specify the split points
Example: var str='12-34-56'; var res=[Link](/-/)) // array of [12, 34, 56]

Positioning Elements
HTML tables can be used for element positioning, but they lack flexibility and are slow to render -
CSS-P was released by W3C in 1997 CSS-P allows us to place any element anywhere on the display,
and move it later .
It provides the means not only to position any element anywhere in the display of a document, but
also to move an element to a new position in the display dynamically, using JavaScript to change the
positioning style properties of the element.
The position of any element can be dictated by the three style properties: position, left, and top -
The three possible values of position are absolute, relative, and static

25
CSE IV-I : R16 UNIT-II JavaScript & DHTML

Absolute Positioning
The absolute value is specified for position when the element is to be placed at a specific place in the
document display without regard to the positions of other elements. For example, if a paragraph of
text is to appear 100 pixels from the left edge and 200 pixels from the top of the display window, the
following element could be used
<p style = "position: absolute; left: 100px; top: 200px;">
- - text - -
</p>
<!DOCTYPE html>
<html>
<head>
<style>
[Link] {
position: relative;
width: 400px;
height: 200px;
border: 3px solid #73AD21;
}

[Link] {
position: absolute;
top: 80px;
right: 0;
width: 200px;
height: 100px;
border: 3px solid #73AD21;
}
</style>
</head>
<body>

<h2>position: absolute;</h2>

<p>An element with position: absolute; is positioned relative to the nearest positioned
ancestor (instead of positioned relative to the viewport, like fixed):</p>
<div class="relative">This div element has position: relative;
<div class="absolute">This div element has position: absolute;</div>
</div>

26
CSE IV-I : R16 UNIT-II JavaScript & DHTML

</body>
</html>

Relative Positioning
If no top and left properties are specified, the element is placed exactly where it would have been
placed if no position property were given. But it can be moved later.
- If top and left properties are given, they are offsets from where it would have placed without the
position property being specified
- If negative values are given for top and left, the displacement is upward and to the left
- Can make superscripts and subscripts

<?xml version = "1.0" encoding = "utf-8" ?>


<!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.0 Strict//EN"
"[Link]

<!-- [Link]
Illustrates relative positioning of elements
-->
<html xmlns = "[Link]
<head>
<title> Relative positioning </title>
</head>
<body style = "font-family: Times; font-size: 24pt;">
<p>More Apples </p>
<p>

27
CSE IV-I : R16 UNIT-II JavaScript & DHTML

Apples are <span style ="position: relative;top:10px; font-family: Times; font-size: 48pt; font-
style: italic; color: red;">
GOOD </span> for you.
</p>
</body>
</html>

Static Positioning
- The default value if position is not specified
- Neither top nor left can be initially set, nor can they be changed later

<!DOCTYPE html>
<html>
<head>
<style>
[Link] {
position: static;
border: 3px solid #73AD21;
}
</style>
</head>
<body>

<h2>position: static;</h2>

<p>An element with position: static; is not positioned in any special way; it is
always positioned according to the normal flow of the page:</p>

<div class="static">

28
CSE IV-I : R16 UNIT-II JavaScript & DHTML

This div element has position: static;


</div>

</body>
</html>

Moving Elements
• If position is set to either absolute or relative, the element can be moved after it is
displayed
• Just change the top and left property values with a script Changing Colors and Fonts
• Background color is controlled by the backgroundColor property
• Foreground color is controlled by the color property
• Can use a function to change these two properties
• Let the user input colors through text buttons
• Have the text elements call the function with the element address (its name) and the new
color Background color:
<input type = "text" size = "10" name = "background" onchange = setColor('background',
[Link])">
• The actual parameter [Link] works because at the time of the call, this is a reference to
the text box (the element in which the call is made)
• So, [Link] is the name of the new color Dynamic Colors and Fonts

Changing fonts
 We can change the font properties of a link by using the mouseover and mouseout events to
trigger a script that makes the changes
 In this case, we can assign the complete script to make the changes to the element’s attribute
(in the HTML)

29
CSE IV-I : R16 UNIT-II JavaScript & DHTML

onmouseover = "[Link] = 'blue';


[Link] = 'italic 16pt Times';"
onmouseout = "[Link] = 'black';
[Link] = 'normal 16pt Times';”
<html>
<head><title>dynamic fonts</title></head>
<body>
<p class ="regText">
The state of<span class = "wordText";
onmouseover = "[Link] = 'blue';
[Link] = 'italic 16pt Times';"
onmouseout = "[Link] = 'black';
[Link] = 'normal 16pt Times';">
Washington
</span>produces many of our nations apples.
</p>
</body>
</html>
Output

with the mouse cursor not over the word

with the mouse cursor over the word

Dynamic Content
The content of an element is accessed through the value property of its associated Java-Script object.
So, changing the content of an element is not essentially different from changing other properties of
the element. We now develop an example that illustrates one use of dynamic content. Assistance to a
browser user filling out a form can be provided with an associated text area, often called a help box.
The content of the help box can change, depending on the placement of the mouse cursor. When the
cursor is placed over a particular input field, the help box can display advice on how the field is to be

30
CSE IV-I : R16 UNIT-II JavaScript & DHTML

filled in. When the cursor is moved away from an input field, the help box content can be changed to
simply indicate that assistance is available. In the next example, an array of messages that can be
displayed in the help box is defined in JavaScript. When the mouse cursor is placed over an input
field, the mouseover event is used to call a handler function that changes the help box content to the
appropriate value (the one associated with the input field). The appropriate value is specified with a
parameter sent to the handler function. The mouseout event is used to trigger the change of the
content of the help box back to the “standard” value. Following is the markup document and
associated JavaScript file:

[Link]
<html>
<head><title>Dynamic values</title>
<script type ="text/javascript" src="[Link]" ></script>
</head>
<body>
<form action = " ">
<p style ="font-weight: bold">
<span style = "font-style:italic">
Customer information
</span>
<br /><br />

<label>
Name:
<input type="text" onmouseover ="message(0)" onmouseout="message(4)" />
</label> <br />
<label>
Email:
<input type="text" onmouseover ="message(1)" onmouseout="message(4)" />
</label>
<br /><br />
<label>
User ID:
<input type="text" onmouseover ="message(2)" onmouseout="message(4)" />
</label><br />
<label>
Password:
<input type="text" onmouseover ="message(3)" onmouseout="message(4)" />
</label><br />
<textarea id="adviceBox" rows ="3" cols="50" style= "postion:absolute; left:250px top:
0px">This box provides advice on filling out the form on this page. Put the mouse cursor over
any input field to get advice.
</textarea>
<br /><br />
<input type ="submit" value ="Submit" />
<input type ="reset" value ="Reset" />
31
CSE IV-I : R16 UNIT-II JavaScript & DHTML

</p>
</form>
</body>
</html>

[Link]
function message(adviceNumber) {
[Link]("adviceBox").value=helpers[adviceNumber];
}
var helpers=["Your name must be in the form: \n \ first name, middle name, last name",
"Your email address must have the form: \ user@domain",
"Your User ID must have at least six characters",
"Your Password must have at least six\ charactres and it must inlclude one digit",
"This Box provides advice on filling out the form on this page. Put the mouse coursor any
input field to get advice"]

32

You might also like