UNIT-II JavaScript
UNIT-II JavaScript
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
2
CSE IV-I : R16 UNIT-II JavaScript & DHTML
3
CSE IV-I : R16 UNIT-II JavaScript & DHTML
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.
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
5
CSE IV-I : R16 UNIT-II JavaScript & DHTML
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:
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
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.
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
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.
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
10
CSE IV-I : R16 UNIT-II JavaScript & DHTML
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
*, /, % Left
+, - Left
==, != Left
===,!== Left
&& Left
|| Left
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 />” );
}
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
13
CSE IV-I : R16 UNIT-II JavaScript & DHTML
For
Syntax : for (initial expression; control expression; increment expression)
statement or compound statement
do-while
Syntax: do statement or compound statement
while (control expression)
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:
• 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
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.
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
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]();
concat: The concat method catenates its actual parameters to the end of the Array object on which it
is called.
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
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
17
CSE IV-I : R16 UNIT-II JavaScript & DHTML
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 />”);
}
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.
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
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.
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
\d [0-9] A digit
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
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
<!-- [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
</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" > [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
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" />
</label> <br />
<label>
Email:
<input type="text" />
</label>
<br /><br />
<label>
User ID:
<input type="text" />
</label><br />
<label>
Password:
<input type="text" />
</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