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

Javascript and dhml module 2

Java

Uploaded by

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

Javascript and dhml module 2

Java

Uploaded by

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

Javascript

What is JavaScript ?
 Javascript is a dynamic computer programming language. It is lightweight and most
commonly used as a part of web pages.
 It allow client-side script to interact with the user and make dynamic pages. It is an
interpreted programming language with object-oriented capabilities.
 JavaScript is a lightweight, interpreted programming language.
 Designed for creating dynamic web applications.
 Complementary to and integrated with HTML.
 Open and cross-platform
Stntax:

<script ...>
JavaScript code
</script>
Example:
<html>
<body>
<script language="javascript" type="text/javascript">

document.write("Hello World!");

</script>
</body>
</html>
Client-side JavaScript
 Client-side JavaScript is the most common form of javascript language. The script
should be included in HTML document for the code to be interpreted by the browser.
 Dynamic web pages can be created by integrating javascript code to HTML content.

 The JavaScript client-side mechanism provides many advantages over traditional CGI
server-side scripts. For example, you might use JavaScript to check if the user has
entered a valid e-mail address in a form field.The JavaScript code is executed when the
user submits the form, and only if all the entries are valid, they would be submitted to the
Web Server.
 JavaScript can be used to trap user-initiated events such as button clicks, link
navigation, and other actions that the user initiates explicitly or implicitly.
Advantages of JavaScript
The merits of using JavaScript are −

 Less server interaction − You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.

 Immediate feedback to the visitors − They don't have to wait for a page reload to see if
they have forgotten to enter something.
 Increased interactivity − You can create interfaces that react when the user hovers over
them with a mouse or activates them via the keyboard.

 Richer interfaces − You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.
Implementation of Java script in HTML Page.

There is a flexibility given to include JavaScript code anywhere in an HTML document.


However the most preferred ways to include JavaScript in an HTML file are as follows −

1. Script in <head>...</head> section.

2. Script in <body>...</body> section.

3. Script in <body>...</body> and <head>...</head> sections.

4. Script in an external file and then include in <head>...</head> section.


1. JavaScript in <head>...</head> section
If you want to have a script run on some event, such as when a user clicks somewhere, then
you will place that script in the head as follows −

<html>
<head>
<script type = "text/javascript">
function sayHello()
{
alert("Hello World")
}
</script>
</head>
<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>

2. JavaScript in <body>...</body> section


If you need a script to run as the page loads so that the script generates content in the page, then
the script goes in the <body> portion of the document. In this case, you would not have any
function defined using JavaScript. Take a look at the following code.

<html>
<head>
</head>

<body>
<script type = "text/javascript">
document.write("Hello World")
</script>

<p>This is web page body </p>


</body>
</html>
3. JavaScript in <body> and <head> Sections
You can put your JavaScript code in <head> and <body> section altogether as follows −

<html>
<head>
<script type = "text/javascript">
function sayHello()
{
alert("Hello World")
}
</script>
</head>

<body>
<script type = "text/javascript">

document.write("Hello World")
</script>

<input type = "button" onclick = "sayHello()" value = "Say Hello" />


</body>
</html>
4. JavaScript in External File
As you begin to work more extensively with JavaScript, you will be likely to find that there are
cases where you are reusing identical JavaScript code on multiple pages of a site.
You are not restricted to be maintaining identical code in multiple HTML files. The script tag
provides a mechanism to allow you to store JavaScript in an external file and then include it into
your HTML files.

Here is an example to show how you can include an external JavaScript file in your HTML
code using script tag and its src attribute.

<html>
<head>
<script type = "text/javascript" src = "filename.js" ></script>
</head>

<body>
.......
</body>
</html>

To use JavaScript from an external file source, you need to write all your JavaScript source
code in a simple text file with the extension ".js" and then include that file as shown above.
For example, you can keep the following content in filename.js file and then you can
use sayHello function in your HTML file after including the filename.js file.

function sayHello()
{
alert("Hello World")
}

JavaScript Data types


One of the most fundamental characteristics of a programming language is the set of data types
it supports. These are the type of values that can be represented and manipulated in a
programming language.

JavaScript allows you to work with three primitive data types −

 Numbers, eg. 123, 120.50 etc.

 Strings of text e.g. "This text string" etc.

 Boolean e.g. true or false.

JavaScript also defines two trivial data types, null and undefined, each of which defines only a
single value. In addition to these primitive data types, JavaScript supports a composite data type
known as object.
JavaScript Variables
 Like many other programming languages, JavaScript has variables. Variables can be
thought of as named containers. You can place data into these containers and then refer
to the data simply by naming the container.
 Before you use a variable in a JavaScript program, you must declare it. Variables are
declared with the var keyword as follows.

<script type = "text/javascript">


var money;
var name;
</script>

You can also declare multiple variables with the same var keyword as follows −
<script type = "text/javascript">
var money, name;
</script>
You can assign a value at the time of initialization as follows.

<script type = "text/javascript">


var name = "Ali";
var money;
money = 2000.50;
</script>
JavaScript Variable Scope
The scope of a variable is the region of your program in which it is defined. JavaScript variables
have only two scopes.
 Global Variables − A global variable has global scope which means it can be
defined anywhere in your JavaScript code.
 Local Variables − A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.
Operators in Java Script
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is
called the operator. JavaScript supports the following types of operators.

1. Arithmetic Operators

2. Comparison Operators

3. Logical (or Relational) Operators

4. Assignment Operators

5. Conditional (or ternary) Operators


1. Arithmetic Operators
JavaScript supports the following arithmetic operators − Assume variable A holds 10 and
variable B holds 20, then −

Sr.No Operator and


Description

1 + (Addition)
Adds two operands
Ex: A + B will give 30
2 - (Subtraction)
Subtracts the second operand from the first
Ex: A - B will give -10

3 * (Multiplication)
Multiply both operands
Ex: A * B will give
200
4 / (Division)
Divide the numerator by the denominator
Ex: B / A will give 2

5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0

6 ++ (Increment)
Increases an integer value by one
Ex: A++ will give 11

7 -- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9

2. Comparison Operators
JavaScript supports the following comparison operators − Assume variable A holds 10 and
variable B holds 20, then −

Sr.No Operator and


Description

1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition
becomes true.
Ex: (A == B) is not true.

2 != (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal,
then the condition becomes true.
Ex: (A != B) is true.

3 > (Greater than)


Checks if the value of the left operand is greater than the value of the right
operand, if yes, then the condition becomes true.
Ex: (A > B) is not true.

4 < (Less than)


Checks if the value of the left operand is less than the value of the right operand, if
yes, then the condition becomes true.
Ex: (A < B) is true.

5 >= (Greater than or Equal to)


Checks if the value of the left operand is greater than or equal to the value of the
right operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.

6 <= (Less than or Equal to)


Checks if the value of the left operand is less than or equal to the value of the
right operand, if yes, then the condition becomes true.
Ex: (A <= B) is true.

3. Logical Operators
JavaScript supports the following logical operators −Assume variable A holds 10 and variable B
holds 20, then −

Sr.No Operator and


Description

1 && (Logical AND)


If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.

2 || (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical
NOT operator will make it false.
Ex: ! (A && B) is false.

4. Bitwise Operators
JavaScript supports the following bitwise operators −Assume variable A holds 2 and variable B
holds 3, then −

Sr.No Operator and


Description

1 & (Bitwise AND)


It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.

2 | (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.

5 << (Left Shift)


It moves all the bits in its first operand to the left by the number of places
specified in the second operand. New bits are filled with zeros. Shifting a value
left by one position is equivalent to multiplying it by 2, shifting two positions is
equivalent to multiplying by 4, and so on.
Ex: (A << 1) is 4.

6 >> (Right Shift)


Binary Right Shift Operator. The left operand’s value is moved right by the
number of bits specified by the right operand.
Ex: (A >> 1) is 1.

7 >>> (Right shift with Zero)


This operator is just like the >> operator, except that the bits shifted in on the
left are always zero.
Ex: (A >>> 1) is 1.
5. Assignment Operators
JavaScript supports the following assignment operators −

Sr.No Operator and


Description

1 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C

2 += (Add and Assignment)


It adds the right operand to the left operand and assigns the result to the left
operand.
Ex: C += A is equivalent to C = C + A

3 −= (Subtract and Assignment)


It subtracts the right operand from the left operand and assigns the result to the left
operand.
Ex: C -= A is equivalent to C = C - A

4 *= (Multiply and Assignment)


It multiplies the right operand with the left operand and assigns the result to the left
operand.
Ex: C *= A is equivalent to C = C * A

5 /= (Divide and Assignment)


It divides the left operand with the right operand and assigns the result to the left
operand.
Ex: C /= A is equivalent to C = C / A

6 %= (Modules and Assignment)


It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A
Miscellaneous Operator
We will discuss two operators here that are quite useful in JavaScript: the conditional
operator (? :) and the typeof operator.
7. Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then executes
one of the two given statements depending upon the result of the evaluation.

Sr.No Operator and


Description

1 ? : (Conditional )

If Condition is true? Then value X : Otherwise value Y

8. typeof Operator
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number,
string, or boolean value and returns true or false based on the evaluation.

Here is a list of the return values for the typeof Operator.


Conditional Statements in JAVASCRIPT

JavaScript supports the following forms of if..else statement −

1. if statement

2. if...else statement

3. if...else if... statement.

1. if statement
The if statement is the fundamental control statement that allows JavaScript to make
decisions and execute statements conditionally.

Syntax
The syntax for a basic if statement is as follows −

if (expression)
{
Statement(s) to be executed if expression is true
}

Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s)
are executed. If the expression is false, then no statement would be not executed. Most of the
times, you will use comparison operators while making decisions.
Example
Try the following example to understand how the if statement works.

<script type = "text/javascript">

var age = 20;

if( age > 18 )


{
document.write("<b>Qualifies for driving</b>");
}
</script>
Output
Qualifies for driving
Set the variable to different value and then try...

2. if...else statement
The 'if...else' statement is the next form of control statement that allows JavaScript to execute
statements in a more controlled way.
Syntax
if (expression)
{
Statement(s) to be executed if expression is true
}
else
{
Statement(s) to be executed if expression is false
}

Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in
the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else
block are executed.
Example
Try the following code to learn how to implement an if-else statement in JavaScript.

<script type = "text/javascript">

var age = 15;


if( age > 18 )
{
document.write("<b>Qualifies for driving</b>");
}
else
{
document.write("<b>Does not qualify for driving</b>");
}
</script>
Output
Does not qualify for driving
Set the variable to different value and then try...

3. if...else if... statement


The if...else if... statement is an advanced form of if…else that allows JavaScript to make a
correct decision out of several conditions.
Syntax
The syntax of an if-else-if statement is as follows −

if (expression 1)
{
Statement(s) to be executed if expression 1 is true
}
else if (expression 2)
{
Statement(s) to be executed if expression 2 is true
}
else if (expression 3)
{
Statement(s) to be executed if expression 3 is true
}
else
{
Statement(s) to be executed if no expression is true
}

There is nothing special about this code. It is just a series of if statements, where each if is a part
of the else clause of the previous statement. Statement(s) are executed based on the true
condition, if none of the conditions is true, then the else block is executed.
Example
Try the following code to learn how to implement an if-else-if statement in JavaScript.

<script type = "text/javascript">


var book = "maths";
if( book == "history" )
{
document.write("<b>History Book</b>");
}
else if( book == "maths" )
{
document.write("<b>Maths Book</b>");
}
else if( book == "economics" )
{
document.write("<b>Economics Book</b>");
}
Else
{
document.write("<b>Unknown Book</b>");
}
</script>

Output
Maths Book
Set the variable to different value and then try...
You can use multiple if...else…if statements, as in the previous chapter, to perform a multiway
branch. However, this is not always the best solution, especially when all of the branches
depend on the value of a single variable.

Starting with JavaScript 1.2, you can use a switch statement which handles exactly this
situation, and it does so more efficiently than repeated if...else ifstatements.
4. switch Statement
The following flow chart explains a switch-case statement works.

The objective of a switch statement is to give an expression to evaluate and several different
statements to execute based on the value of the expression. The interpreter checks each
case against the value of the expression until a match is found. If nothing matches, a
default condition will be used.
switch (expression)
{
case condition 1:
statement(s)
break;

case condition 2:
statement(s)
break;
...

case condition n:
statement(s)
break;

default: statement(s)
}
The break statements indicate the end of a particular case. If they were omitted, the
interpreter would continue executing each statement in each of the following cases.

We will explain break statement in Loop Control chapter.


Example
Try the following example to implement switch-case statement.

<script type = "text/javascript">


var grade = 'A';
document.write("Entering switch block<br />");
switch (grade)
{
case 'A':
document.write("Good job<br />");
break;

case 'B':
document.write("Pretty good<br />");
break;

case 'C':
document.write("Passed<br />");
break;

case 'D':
document.write("Not so good<br />");
break;

case 'F':
document.write("Failed<br />");
break;

default:
document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
</script>
Output
Entering switch block
Good job
Exiting switch block
Set the variable to different value and then try...

Looping in JavaScript
While writing a program, you may encounter a situation where you need to perform an action
over and over again. In such situations, you would need to write loop statements to reduce the
number of lines.
JavaScript supports all the necessary loops to ease down the pressure of programming.
1. The while Loop
The most basic loop in JavaScript is the while loop which would be discussed in this chapter.
The purpose of a while loop is to execute a statement or code block repeatedly as long as
an expression is true. Once the expression becomes false, the loop terminates.
Syntax
The syntax of while loop in JavaScript is as follows −

while (expression)
{
Statement(s) to be executed if expression is true
}
Example
Try the following example to implement while loop.

<script type="text/javascript">
var i = 0;
while (i < 10)
{
document.write( i + "<br />");
count++;
}

</script>

Output
1
2
3
4
5
6
7
8
9
10
2. The do...while Loop
The do...while loop is similar to the while loop except that the condition check happens at the
end of the loop. This means that the loop will always be executed at least once, even if the
condition is false.
Syntax
The syntax for do-while loop in JavaScript is as follows −

Do
{
Statement(s) to be executed;
}
while (expression);
Example
<script type="text/javascript">
var i= 0;
do
{
document.write( i + "<br />");
i++;
}
while (i < 5);
</script>

Output
1
2
3
4
5
3. The 'for' loop

It is the most compact form of looping. It includes the following three important parts −
 The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.

 The test statement which will test if a given condition is true or not. If the condition is
true, then the code given inside the loop will be executed, otherwise the control will
come out of the loop.
 The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
Syntax
The syntax of for loop is JavaScript is as follows −

for (initialization; test condition; iteration statement)


{
Statement(s) to be executed if test condition is true
}
Example
Try the following example to learn how a for loop works in JavaScript.

<script type = "text/javascript">


var i;

for(i = 0; i < 5; i++)


{
document.write( i );
document.write("<br />");
}
</script>

Output
1
2
3
4
The break Statement
The break statement, which was briefly introduced with the switch statement, is used to exit a
loop early, breaking out of the enclosing curly braces.
Example
The following example illustrates the use of a break statement with a while loop. Notice how
the loop breaks out early once x reaches 5 and reaches to document.write (..) statement just
below to the closing curly brace −

<script type="text/javascript">
var x = 1;
while (x < 20)
{
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
</script>
Output
1
2
3
4
5
The continue Statement
The continue statement tells the interpreter to immediately start the next iteration of the loop
and skip the remaining code block. When a continuestatement is encountered, the program flow
moves to the loop check expression immediately and if the condition remains true, then it starts
the next iteration, otherwise the control comes out of the loop.
Example
This example illustrates the use of a continue statement with a while loop. Notice how
the continue statement is used to skip printing when the index held in variable x reaches 5 −

<script type="text/javascript">
var x = 1;
while (x < 10)
{
x = x + 1;

if (x == 5){
continue; // skip rest of the loop body
}
document.write( x + "<br />");
}
</script>

Output
Entering the loop
2
3
4
6
7
8
9
10
FUNTIONS IN JAVASCRIPT
 A function is a group of programming code which can be called anywhere in your
program. This eliminates the need of writing the same code again and again. It helps
programmers in writing modular codes. Functions allow a programmer to divide a big
program into a number of small and manageable functions.
 Like any other advanced programming language, JavaScript also supports all the
features necessary to write modular code using functions.

 JavaScript allows us to write our own functions as well. This section explains how to
write your own functions in JavaScript.
Function Definition
Before we use a function, we need to define it. The most common way to define a function in
JavaScript is by using the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded by curly braces.
Syntax
The basic syntax is shown here.

<script type="text/javascript">
function functionname(parameter-list)
{
statements
}
</script>
Example
Try the following example. It defines a function called sayHello that takes no parameters −

<script type="text/javascript">
function sayHello()
{
alert("Hello there");
}
</script>

Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the name of
that function as shown in the following code.
<html>
<head>

<script type="text/javascript">
function sayHello()
{
document.write ("Hello there!");
}
</script>

</head>
<body>
<p>Click the following button to call the function</p>

<form>
<input type="button" onclick="sayHello()" value="Say Hello">
</form>

<p>Use different text in write method and then try...</p>


</body>
</html>

Events In JAVASCRIPT

What is an Event ?
 JavaScript's interaction with HTML is handled through events that occur when the user
or the browser manipulates a page.

 When the page loads, it is called an event. When the user clicks a button, that click too is
an event. Other examples include events like pressing any key, closing a window,
resizing a window, etc.
 Developers can use these events to execute JavaScript coded responses, which cause
buttons to close windows, messages to be displayed to users, data to be validated, and
virtually any other type of response imaginable.
 Events are a part of the Document Object Model (DOM) Level 3 and every HTML
element contains a set of events which can trigger JavaScript Code.

Here we will see a few examples to understand a relation between Event and JavaScript −
1. onclick Event Type
This is the most frequently used event type which occurs when a user clicks the left button of
his mouse. You can put your validation, warning etc., against this event type.

Example
Try the following example.

<html>
<head>

<script type="text/javascript">
function sayHello()
{
alert("Hello World")
}
</script>

</head>

<body>
<p>Click the following button and see result</p>

<form>
<input type="button" onclick="sayHello()" value="Say Hello" />
</form>

</body>
</html>
2.onsubmit Event type
onsubmit is an event that occurs when you try to submit a form. You can put your form
validation against this event type.

Example
The following example shows how to use onsubmit. Here we are calling a validate() function
before submitting a form data to the webserver. If validate() function returns true, the form will
be submitted, otherwise it will not submit the data.

Try the following example.

<html>
<head>
<script type="text/javascript">
function validation()
{

return either true or false


}
</script>

</head>
<body>

<form method="POST" action="t.cgi" onsubmit="return validate()">


.......
<input type="submit" value="Submit" />
</form>

</body>
</html>

3.onmouseover and onmouseout


These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and
the onmouseout triggers when you move your mouse out from that element. Try the following
example.

<html>
<head>

<script type="text/javascript">

function over()
{
document.write ("Mouse Over");
}

function out()
{
document.write ("Mouse Out");
}

</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>

<div onmouseover="over()" onmouseout="out()">


<h2> This is inside the division </h2>
</div>

</body>
</html>

Types of Dialog Boxes in JavaScript


JavaScript supports three important types of dialog boxes. These dialog boxes can be used to
raise an alert, or to get confirmation on any input or to have a kind of input from the users. Here
we will discuss each dialog box one by one.
1. Alert Dialog Box
An alert dialog box is mostly used to give a warning message to the users. For example, if one
input field requires to enter some text but the user does not provide any input, then as a part of
validation, you can use an alert box to give a warning message.
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one
button "OK" to select and proceed.

Example
<html>
<head>

<script type="text/javascript">
<!--
function Warn()
{
alert ("This is a warning message!");

}
</script>

</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="Warn();" />
</form>

</body>
</html>
Output

2. Confirmation Dialog Box


A confirmation dialog box is mostly used to take user's consent on any option. It displays a
dialog box with two buttons: Cancel.
If the user clicks on the OK button, the window method confirm() will return true. If the user
clicks on the Cancel button, then confirm() returns false. You can use a confirmation dialog
box as follows.

Example
<html>
<head>

<script type="text/javascript">
function getConfirmation()
{
var retVal = confirm("Do you want to continue ?");
if( retVal == true )
{
document.write ("User wants to continue!");
return true;
}
Else
{
document.write ("User does not want to continue!");
return false;
}
}
</script>

</head>
<body>
<p>Click the following button to see the result: </p>

<form>
<input type="button" value="Click Me" onclick="getConfirmation();" />
</form>

</body>
</html>

Output

3. Prompt Dialog Box


The prompt dialog box is very useful when you want to pop-up a text box to get user input.
Thus, it enables you to interact with the user. The user needs to fill in the field and then click
OK.
This dialog box is displayed using a method called prompt() which takes two parameters: (i) a
label which you want to display in the text box and (ii) a default string to display in the text
box.

This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window
method prompt() will return the entered value from the text box. If the user clicks the Cancel
button, the window method prompt()returns null.
Example
The following example shows how to use a prompt dialog box −

<html>
<head>

<script type="text/javascript">
<!--
function getValue()
{
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
</script>

</head>

<body>
<p>Click the following button to see the result: </p>

<form>
<input type="button" value="Click Me" onclick="getValue();" />
</form>

</body>
</html>
Output

JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method).
For example: car, pen, bike, chair, glass, keyboard, monitor etc.

JavaScript is an object-based language. Everything is an object in JavaScript.

JavaScript is template based not class based. Here, we don't create class to get the
object. But, we direct create objects.

Creating Objects in JavaScript


There are 3 ways to create objects.

1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

1) JavaScript Object by object literal


The syntax of creating object using object literal is given below:

object={property1:value1,property2:value2.....propertyN:valueN}

As you can see, property and value is separated by : (colon).

Let’s see the simple example of creating object in JavaScript.

<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

2) By creating instance of Object


The syntax of creating object directly is given below:

var objectname=new Object();

Here, new keyword is used to create object.

the example of creating object directly.

<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

3) By using an Object constructor


Here, you need to create function with arguments. Each argument value can be
assigned in the current object by using this keyword.

The this keyword refers to the current object.

The example of creating object by object constructor is given below.

<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);


</script>

The Date Object

The Date object is a datatype built into the JavaScript language. Date objects are created with
the new Date( ) as shown below.

Once a Date object is created, a number of methods allow you to operate on it. Most methods
simply allow you to get and set the year, month, day, hour, minute, second, and millisecond
fields of the object, using either local time or UTC (universal, or GMT) time.

You can use any of the following syntaxes to create a Date object using Date() constructor.

 new Date( )
 new Date(milliseconds)
 new Date(datestring)

INTRODUCTION TO DHTML
DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic HTML.

Dynamic HTML is not a markup or programming language but it is a term that


combines the features of various web development technologies for creating the web
pages dynamic and interactive.

The DHTML application was introduced by Microsoft with the release of the 4 th version
of IE (Internet Explorer) in 1997.

Components of Dynamic HTML


DHTML consists of the following four components or languages:
o HTML 4.0
o CSS
o JavaScript
o DOM.

HTML 4.0

HTML is a client-side markup language, which is a core component of the DHTML. It


defines the structure of a web page with various defined basic elements or tags.

CSS

CSS stands for Cascading Style Sheet, which allows the web users or developers for
controlling the style and layout of the HTML elements on the web pages.

JavaScript

JavaScript is a scripting language which is done on a client-side. The various browser


supports JavaScript technology. DHTML uses the JavaScript technology for accessing,
controlling, and manipulating the HTML elements. The statements in JavaScript are
the commands which tell the browser for performing an action.

DOM

DOM is the document object model. It is a w3c standard, which is a standard


interface of programming for HTML. It is mainly used for defining the objects and
properties of all elements in HTML.

Uses of DHTML
Following are the uses of DHTML (Dynamic HTML):

o It is used for designing the animated and interactive web pages that are developed in
real-time.
o DHTML helps users by animating the text and images in their documents.
o It allows the authors for adding the effects on their pages.
o It also allows the page authors for including the drop-down menus or rollover buttons.
o This term is also used to create various browser-based action games.
o It is also used to add the ticker on various websites, which needs to refresh their
content automatically.
Features of DHTML
Following are the various characteristics or features of DHTML (Dynamic HTML):

o Its simplest and main feature is that we can create the web page dynamically.
o Dynamic Style is a feature, that allows the users to alter the font, size, color, and
content of a web page.
o It provides the facility for using the events, methods, and properties. And, also
provides the feature of code reusability.
o It also provides the feature in browsers for data binding.
o Using DHTML, users can easily create dynamic fonts for their web sites or web pages.
o With the help of DHTML, users can easily change the tags and their properties.
o The web page functionality is enhanced because the DHTML uses low-bandwidth
effect.

Difference between HTML and DHTML


Following table describes the differences between HTML and DHTML:

HTML (Hypertext Markup language) DHTML (Dynamic Hypertext Markup language)

1. HTML is simply a markup language. 1. DHTML is not a language, but it is a set of


technologies of web development.

2. It is used for developing and creating 2. It is used for creating and designing the
web pages. animated and interactive web sites or pages.

3. This markup language creates static 3. This concept creates dynamic web pages.
web pages.

4. It does not contain any server-side 4. It may contain the code of server-side
scripting code. scripting.

5. The files of HTML are stored with 5. The files of DHTML are stored with
the .html or .htm extension in a system. the .dhtm extension in a system.

6. A simple page which is created by a 6. A page which is created by a user using the
user without using the scripts or styles HTML, CSS, DOM, and JavaScript technologies
called as an HTML page. called a DHTML page.

7. This markup language does not need 7. This concept needs database connectivity
database connectivity. because it interacts with users.

DHTML JavaScript
JavaScript can be included in HTML pages, which creates the content of the page as
dynamic. We can easily type the JavaScript code within the <head> or <body> tag
of a HTML page. If we want to add the external source file of JavaScript, we can easily
add using the <src> attribute.

Following are the various examples, which describes how to use the JavaScript
technology with the DHTML:

Document.write() Method
The document.write() method of JavaScript, writes the output to a web page.

Example 1: The following example simply uses the document.write() method of


JavaScript in the DHTML. In this example, we type the JavaScript code in
the <body> tag.

<HTML>
<head>
<title>
Method of a JavaScript
</title>
</head>
<body>
<script type="text/javascript">
document.write("JavaTpoint");
</script>
</body> </html>

You might also like