Javascript and dhml module 2
Javascript and dhml module 2
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.
<html>
<head>
<script type = "text/javascript">
function sayHello()
{
alert("Hello World")
}
</script>
</head>
<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>
<html>
<head>
</head>
<body>
<script type = "text/javascript">
document.write("Hello World")
</script>
<html>
<head>
<script type = "text/javascript">
function sayHello()
{
alert("Hello World")
}
</script>
</head>
<body>
<script type = "text/javascript">
document.write("Hello World")
</script>
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 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.
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.
1. Arithmetic Operators
2. Comparison Operators
4. Assignment Operators
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 −
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. Logical Operators
JavaScript supports the following logical operators −Assume variable A holds 10 and variable B
holds 20, then −
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 −
2 | (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.
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
1 ? : (Conditional )
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.
1. if statement
2. if...else 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.
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.
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.
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.
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 −
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>
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.
<html>
<head>
<script type="text/javascript">
function validation()
{
</head>
<body>
</body>
</html>
<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>
</body>
</html>
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
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
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 template based not class based. Here, we don't create class to get the
object. But, we direct 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)
object={property1:value1,property2:value2.....propertyN:valueN}
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
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.
The DHTML application was introduced by Microsoft with the release of the 4 th version
of IE (Internet Explorer) in 1997.
HTML 4.0
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
DOM
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.
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.
<HTML>
<head>
<title>
Method of a JavaScript
</title>
</head>
<body>
<script type="text/javascript">
document.write("JavaTpoint");
</script>
</body> </html>