[go: up one dir, main page]

0% found this document useful (0 votes)
22 views51 pages

Unit-2

The document provides an introduction to DHTML (Dynamic Hypertext Markup Language) and JavaScript, explaining the differences between static and dynamic web pages. It outlines the basic components needed to create static websites using HTML, CSS, and JavaScript, and describes the features and uses of DHTML for creating interactive web content. Additionally, it includes examples of JavaScript integration with HTML for dynamic content manipulation and event handling.

Uploaded by

espinozaden45
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)
22 views51 pages

Unit-2

The document provides an introduction to DHTML (Dynamic Hypertext Markup Language) and JavaScript, explaining the differences between static and dynamic web pages. It outlines the basic components needed to create static websites using HTML, CSS, and JavaScript, and describes the features and uses of DHTML for creating interactive web content. Additionally, it includes examples of JavaScript integration with HTML for dynamic content manipulation and event handling.

Uploaded by

espinozaden45
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
You are on page 1/ 51

2.

Introduction to DHTML &Java Script

2.1 Static, Dynamic and Active Page

Example Static HTML File

A static website has fixed content

It does not require programming languages to build one.

It is the easiest form of website to create.

Static websites are built of HTML, CSS, and JavaScript.

Why create a static website?

Static websites are quick and easy to create.

It is cheap to host.

Static websites are secure.

It is fun and you can create awesome sites with HTML, CSS, and

JavaScript. What do I need to know to build a static website

HTML, CSS and JavaScript are the basic languages to build any

website. 1. Create the structure with HTML.

The first thing you have to learn, is HTML, which is the standard markup language for
creating web pages.

2. Style with CSS.

The next step is to learn CSS, to set the layout of your web page with beautiful colors,
fonts, and much more.

3. Make it interactive with JavaScript.

After studying HTML and CSS, you should learn JavaScript to create dynamic and
interactive web pages for your users.

EXAMPLE: -

<!DOCTYPE html>

<html lang="en">
<head>
<!-- Declared Vars To Go Here -->

<meta charset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Metadata -->

<meta name="description" content="">

<meta name="author" content="">

<link rel="icon" href="mysource_files/favicon.ico">

<!-- Page Name and Site Name -->

<title>Page Name - Squiz Matrix HTML Example</title>

<!-- CSS -->

<link
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
rel="stylesheet">

<link href="mysource_files/style.css" rel="stylesheet">

</head>

<body>
<div class="container">
<header class="header clearfix" style="background-color: #ffffff">

<!-- Main Menu -->

<nav>

<ul class="nav nav-pills pull-right">

<li class="active"><a href="#">Home</a></li>

<li><a href="#">About</a></li>

<li><a href="#">Contact</a></li>

</ul>

</nav>

<!-- Site Name -->

<h1 class="h3 text-muted">Site Name</h1>

<!-- Breadcrumbs -->

<ol class="breadcrumb">

<li><a href="#">Home</a></li>

<li><a href="#">Level 1</a></li>

<li class="active">Level 2</li>

</ol>

</header>
<div class="page-heading">
<!-- Page Heading -->

<h1>Page Heading</h1>

</div>

<div class="row">

<div class="col-sm-3">

<!-- Sub Navigation -->

<ul class="nav nav-pills nav-stacked"> <li><a

href="#">Level 2</a></li> <li class="active"><a

href="#">Level 2</a> <ul>

<li><a href="#">Level 3</a></li>

<li><a href="#">Level 3</a></li> <li><a

href="#">Level 3</a></li> </ul>

</li>

<li><a href="#">Level 2</a></li>

</ul>

</div>
<div class="col-sm-6">
<div class="page-contents">

<!-- Design Body -->

<h2>Sub Heading</h2>

<p>Donec id elit non mi porta gravida at eget metus. Maecenas faucibus mollis
interdum.</p>

<h4>Sub Heading</h4>

<p>Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Cras mattis consectetur
purus sit amet fermentum.</p>

<h4>Sub Heading</h4>

<p>Maecenas sed diam eget risus varius blandit sit amet non magna.</p>

</div>

</div>

<div class="col-sm-3">

<!-- Login Section -->

<h2>Login</h2>

<!-- Search Section -->

<h2>Search</h2>
<!-- Nested Right Column Content -->
</div>

</div>

<footer class="footer">

<p class="pull-right">

<!-- Last Updated Design Area-->

Last Updated: Wednesday, January 6, 2016

</p>

<p>&copy; 2016 Company, Inc.</p>

</footer>

</div> <!-- /container -->

</body>

</html>

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 4th 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
the .html or .htm extension in a system. .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
called as an HTML page. technologies 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.

EXAMPLE: -

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

JavaScript and HTML event

A JavaScript code can also be executed when some event occurs. Suppose, a user clicks an
HTML element on a webpage, and after clicking, the JavaScript function associated with that
HTML element is automatically invoked. And, then the statements in the function are
performed.
Example 1:

The following example shows the current date and time with the JavaScript and HTML event
(Onclick). In this example, we type the JavaScript code in the <head> tag.

EXAMPLE: -

1. <html>
2. <head>
3. <title>
4. DHTML with JavaScript
5. </title>
6. <script type="text/javascript">
7. function dateandtime()
8. {
9. alert(Date());
10. }
11. </script>
12. </head>
13. <body bgcolor="orange">
14. <font size="4" color="blue">
15. <center> <p>
16. Click here # <a href="#" onClick="dateandtime();"> Date and Time </a>
17. # to check the today's date and time.
18. </p> </center>
19. </font>
20. </body>
21. </html>

Explanation:

In the above code, we displayed the current date and time with the help of JavaScript in
DHTML. In the body tag, we used the anchor tag, which refers to the page itself. When you
click on the link, then the function of JavaScript is called.

In the JavaScript function, we use the alert () method in which we type the date () function.
The date function shows the date and time in the alert dialog box on the web page.

JavaScript and HTML DOM

With version 4 of HTML, JavaScript code can also change the inner content and attributes of
the HTML event.
Example 1:
This example checks the Grade of a student according to the percentage criteria with the
JavaScript and HTML DOM. In this example, we type the code of a JavaScript in the <body>
tag.

EXAMPLE: -

<html>
<head>
<title> Check Student Grade
</title>
</head>

<body>
<p>Enter the percentage of a Student:</p>
<input type="text" id="percentage">
<button type="button" onclick="checkGrade()">
Find Grade
</button>
<p id="demo"></p>
<script type="text/javascript">
function checkGrade() {
var x,p, text;
p = document.getElementById("percentage").value;

x=parseInt(p);

if (x>90 && x <= 100) {


document.getElementById("demo").innerHTML = "A1";
} else if (x>80 && x <= 90) {
document.getElementById("demo").innerHTML = "A2";
} else if (x>70 && x <= 80) {
document.getElementById("demo").innerHTML = "A3";
}
}
</script>
</body>
</html>

Explanation:

In the above code, we check the student’s Grade with the help of JavaScript in DHTML. In
the JavaScript code, we used the checkGrade() method, which is invoked when we click on
the button. In this function, we stored the value in variable p. The value is taken in the input
field. When the value is stored, then we convert the value of p into integer and store the
conversion value in x, because the value in p is text.
After that, we used the if-else-if statement for finding the grade according to the percentage.
CSS with JavaScript in DHTML

With version 4 of HTML, JavaScript code can also change the style such as size, color, and
face of an HTML element.

Example 1:

The following example changes the color of a text.

<html>
<head>
<title>
getElementById.style.property example
</title>
</head>
<body>
<p id="demo"> This text changes color when click on the following different
buttons. </p>
<button onclick="change_Color('green');"> Green </button>
<button onclick="change_Color('blue');"> Blue </button>
<script type="text/javascript">

function change_Color(newColor) {
var element = document.getElementById('demo').style.color = newColor;
}
</script>
</body>
</html>

Explanation:

In the above code, we changed the color of a text by using the following syntax:

1. document.getElementById('demo').style.property=new_value;.

The above syntax is used in the JavaScript function, which is performed or called when we
clicked on the HTML buttons. The different HTML buttons specify the color of a text.

DHTML CSS

We can easily use the CSS with the DHTML page with the help of JavaScript and HTML
DOM. With the help of this.style.property=new style statement, we can change the style of
the currently used HTML element. Or, we can also update the style of any particular HTML
element by document.getElementById(id).style.property = new_style statement.
Example 1:

The following example uses the DHTML CSS for changing the style of current

element: <html>

<head>

<title>

Changes current HTML element

</title>

</head>

<body>

<center>

<h1 onclick="this.style.color='blue'"> This is a JavaTpoint Site </h1>

<center>

</body>

</html>

Explanation:

In the above code, we used the this.style.color='blue' statement, which shows the color of a
text as blue.

Example 2:

The following example uses the DHTML CSS for changing the style of the HTML element:

<html>
<head>
<title>
changes the particular HTML element example
</title>
</head>
<body>
<p id="demo"> This text changes color when click on the following different
buttons. </p>
<button onclick="change_Color('green');"> Green </button>
<button onclick="change_Color('blue');"> Blue </button>
<script type="text/javascript">
function change_Color(newColor) {
var element = document.getElementById('demo').style.color = newColor;
}
</script>
</body>
</html>

Explanation:

In the above code, we used the var element =


document.getElementById('demo').style.color = newColor; statement, which changes the
color of a text as green and blue according to the buttons.

2.2 DHTML Events

An event is defined as changing the occurrence of an object.

It is compulsory to add the events in the DHTML page. Without events, there will be no
dynamic content on the HTML page. The event is a term in the HTML, which triggers the
actions in the web browsers.

Suppose, any user clicks an HTML element, then the JavaScript code associated with that
element is executed. Actually, the event handlers catch the events performed by the user and
then execute the code.

Example of events:

1. Click a button.
2. Submitting a form.
3. An image loading or a web page loading, etc.

Following table describes the Event Handlers used in the DHTML:


S.No. Event When it occurs

1. onabort It occurs when the user aborts the page or media file loading.

2. onblur It occurs when the user leaves an HTML object.

3. onchange It occurs when the user changes or updates the value of an object.

4. onclick It occurs or triggers when any user clicks on an HTML element.

5. ondblclick It occurs when the user clicks on an HTML element two times
together.
6. onfocus It occurs when the user focuses on an HTML element. This event
handler works opposite to onblur.

7. onkeydown It triggers when a user is pressing a key on a keyboard device.


This event handler works for all the keys.

8. onkeypress It triggers when the users press a key on a keyboard. This event
handler is not triggered for all the keys.

9. onkeyup It occurs when a user released a key from a keyboard after


pressing on an object or element.

10. onload It occurs when an object is completely loaded.

11. onmousedown It occurs when a user presses the button of a mouse over an
HTML element.

12. onmousemove It occurs when a user moves the cursor on an HTML object.

13. onmouseove It occurs when a user moves the cursor over an HTML object.
r

14. onmouseout It occurs or triggers when the mouse pointer is moved out of an
HTML element.

15. onmouseup It occurs or triggers when the mouse button is released over an
HTML element.

16. onreset It is used by the user to reset the form.

17. onselect It occurs after selecting the content or text on a web page.

18. onsubmit It is triggered when the user clicks a button after the submission of
a form.

19. onunload It is triggered when the user closes a web page.

Following are the different examples using the different event handlers, which helps us to
understand the concept of DHTML events:

Example 1:

This example uses the onclick event handler, which is used to change the text after clicking.
<html>
<head>
<title>
Example of onclick event
</title>
<script type="text/javascript">
function ChangeText(ctext)
{
ctext.innerHTML=" Hi JHTML! ";
}
</script>
</head>
<body>
<font color="red"> Click on the Given text for changing it: <br>
</font>
<font color="blue">
<h1 onclick="ChangeText(this)"> Hello World! </h1>
</font>
</body>
</html>

Example 2:

This example uses the onsubmit event handler, which gives an alert after clicking on a submit
button.
<html>
<head>
<title>
Example of onsubmit event
</title>
</head>
<body>
<form onsubmit="Submit_Form()">
<label> Enter your name: </label>
<input type="text">
<label> Enter your Roll no: </label>
<input type="Number">
<input type="submit" value="submit">
</form>
<script type="text/javascript">
function Submit_Form()
{
alert(" Your form is submitted");
}
</script>
</body>
</html>
DHTML DOM

DHTML DOM stands for Dynamic HTML 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. It also defines the
methods for accessing the HTML elements.

Example:

The following program helps in understanding the concept of DHTML DOM. This example
changes the color of text and displays the text in red colour automatically.

<html>
<head>
<title>
Example of DHTML DOM
</title>
</head>
<body>
<font color = "blue">
<p id="demo"> This text changes color when the page loaded. </p>
</font>
<script type="text/javascript">
document.getElementById('demo').style.color = "red";
</script>
</body>
</html>

Advantages of DHTML

Following are the various benefits or the advantages of DHTML (Dynamic HTML):

o Those web sites and web pages which are created using this concept are fast. o There is

no plug-in required for creating the web page dynamically. o Due to the low-bandwidth
effect by the dynamic HTML, the web page functionality is enhanced.
o This concept provides advanced functionalities than the static HTML. o It is

highly flexible, and the user can make changes easily in the web pages.
Disadvantages of DHTML

Following are the various disadvantages or limitations of DHTML (Dynamic HTML):

o The scripts of DHTML does not run properly in various web browsers. Or in simple
words, we can say that various web browsers do not support the DHTML. It is only
supported by the latest browsers.
o The coding of those websites that are created using DHTML is long and complex. o
For understanding the DHTML, users must know about HTML, CSS, and JavaScript. If
any user does not know these languages, then it is a time-consuming and long process in
itself.

2.2.1 Window, Form, Keyboard, Mouse

The window object represents a window in browser. An object of window is created


automatically by the browser.

Window is the object of browser; it is not the object of JavaScript. The JavaScript objects
are string, array, date etc.

Methods of window object

The important methods of window object are as follows:


Method Description

alert() displays the alert box containing message with ok button.

confirm() displays the confirm dialog box containing message with ok and cancel button.

prompt() displays a dialog box to get input from the user.

open() opens the new window.

close() closes the current window.

setTimeout() performs action after specified time like calling function, evaluating
expressions etc.

Example of alert() in javascript

It displays alert dialog box. It has message and ok button.

1. <script type="text/javascript">
2. function msg(){
3. alert("Hello Alert Box");
4. }
5. </script>
6. <input type="button" value="click" onclick="msg()"/>

Example of confirm() in javascript

It displays the confirm dialog box. It has message with ok and cancel buttons.

1. <script type="text/javascript">
2. function msg(){
3. var v= confirm("Are u sure?");
4. if(v==true){
5. alert("ok");
6. }
7. else{
8. alert("cancel");
9. }
10.
11. }
12. </script>
13.
14. <input type="button" value="delete record" onclick="msg()"/>

Example of prompt() in javascript

It displays prompt dialog box for input. It has message and textfield.

1. <script type="text/javascript">
2. function msg(){
3. var v= prompt("Who are you?");
4. alert("I am "+v);
5.
6. }
7. </script>
8.
9. <input type="button" value="click" onclick="msg()"/>
Example of open() in javascript

It displays the content in a new window.

1. <script type="text/javascript">
2. function msg(){
3. open("https://www.youtube.com/");
4. }
5. </script>
6. <input type="button" value="youtube" onclick="msg()"/>

Example of setTimeout() in javascript

It performs its task after the given milliseconds.

1. <script type="text/javascript">
2. function msg(){
3. setTimeout(
4. function(){
5. alert("Welcome to Javatpoint after 2 seconds")
6. },2000);
7.
8. }
9. </script>
10.
11. <input type="button" value="click" onclick="msg()"/>
HTML Form

An HTML form is a section of a document which contains controls such as text fields,
password fields, checkboxes, radio buttons, submit button, menus etc.

An HTML form facilitates the user to enter data that is to be sent to the server for processing
such as name, email address, password, phone number, etc.

Why use HTML Form

HTML forms are required if you want to collect some data from of the site visitor.

For example: If a user wants to purchase some items on internet, he/she must fill the form
such as shipping address and credit/debit card details so that item can be sent to the given
address.
HTML Form Syntax
1. <form action="server url" method="get|post">
2. //input controls e.g. textfield, textarea, radiobutton, button
3. </form>
HTML Form Tags

Let's see the list of HTML 5 form tags.


Tag Description

<form> It defines an HTML form to enter inputs by the used side.

<input> It defines an input control.

<textarea> It defines a multi-line input control.

<label> It defines a label for an input element.

<fieldset> It groups the related element in a form.

<legend> It defines a caption for a <fieldset> element.

<select> It defines a drop-down list.

<optgroup> It defines a group of related options in a drop-down list.

<option> It defines an option in a drop-down list.

<button> It defines a clickable button.

HTML 5 Form Tags

Let's see the list of HTML 5 form tags.


Tag Description

<datalist> It specifies a list of pre-defined options for input control.

<keygen> It defines a key-pair generator field for forms.


<output> It defines the result of a calculation.

HTML <form> element

The HTML <form> element provide a document section to take input from user. It provides
various interactive controls for submitting information to web server such as text field, text
area, password field, etc.

Note: The <form> element does not itself create a form but it is container to contain all
required form elements, such as <input>, <label>, etc.

Syntax:

1. <form>
2. //Form elements
3. </form>
HTML <input> element

The HTML <input> element is fundamental form element. It is used to create form fields, to
take input from user. We can apply different input filed to gather different information form
user. Following is the example to show the simple text input.

Example:
1. <body>
2. <form>
3. Enter your name <br>
4. <input type="text" name="username">
5. </form>
6. </body>
HTML TextField Control

The type="text" attribute of input tag creates textfield control also known as single line
textfield control. The name attribute is optional, but it is required for the server side
component such as JSP, ASP, PHP etc.

1. <form>
2. First Name: <input type="text" name="firstname"/> <br/>
3. Last Name: <input type="text" name="lastname"/> <br/> 4.
</form>
Note: If you will omit 'name' attribute then the text filed input will not be submitted to
server.
HTML <textarea> tag in form

The <textarea> tag in HTML is used to insert multiple-line text in a form. The size of
<textarea> can be specify either using "rows" or "cols" attribute or by CSS.

Example:

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Form in HTML</title>
5. </head>
6. <body>
7. <form>
8. Enter your address:<br>
9. <textarea rows="2" cols="20"></textarea>
10. </form>
11. </body>
12. </html>
Label Tag in Form

It is considered better to have label in form. As it makes the code parser/browser/user friendly.

If you click on the label tag, it will focus on the text control. To do so, you need to have for
attribute in label tag that must be same as id attribute of input tag.
NOTE: It is good to use <label> tag with form, although it is optional but if you will use
it, then it will provide a focus when you tap or click on label tag. It is more worthy with
touchscreens.
1. <form>
2. <label for="firstname">First Name: </label> <br/>
3. <input type="text" id="firstname" name="firstname"/> <br/> 4. <label
for="lastname">Last Name: </label>
5. <input type="text" id="lastname" name="lastname"/> <br/> 6. </form>

HTML Password Field Control

The password is not visible to the user in password field control.


1. <form>
2. <label for="password">Password: </label>
3. <input type="password" id="password" name="password"/> <br/> 4. </form>

HTML 5 Email Field Control

The email field in new in HTML 5. It validates the text for correct email address. You must
use @ and . in this field.

1. <form>
2. <label for="email">Email: </label>
3. <input type="email" id="email" name="email"/> <br/> 4. </form>

Note: If we will not enter the correct email, it will display error

like: Radio Button Control

The radio button is used to select one option from multiple options. It is used for selection of
gender, quiz questions etc.

If you use one name for all the radio buttons, only one radio button can be selected at a

time. Using radio buttons for multiple options, you can only choose a single option at a

time.

1. <form>
2. <label for="gender">Gender: </label>
3. <input type="radio" id="gender" name="gender" value="male"/>M ale
4. <input type="radio" id="gender" name="gender" value="female"/>Female <br/>
5. </form>

Checkbox Control

The checkbox control is used to check multiple options from given checkboxes.

1. <form>
2. Hobby:<br>
3. <input type="checkbox" id="cricket" name="cricket" value="cricket" />
4. <label for="cricket">Cricket</label> <br>
5. <input type="checkbox" id="football" name="football" value="footb all"/>
6. <label for="football">Football</label> <br>
7. <input type="checkbox" id="hockey" name="hockey" value="hocke y"/>
8. <label for="hockey">Hockey</label>
9. </form>

Note: These are similar to radio button except it can choose multiple options at a time
and radio button can select one button at a time, and its display.

Submit button control

HTML <input type="submit"> are used to add a submit button on web page. When user
clicks on submit button, then form get submit to the server.

Syntax:

1. <input type="submit" value="submit">

The type = submit , specifying that it is a submit button

The value attribute can be anything which we write on button on web page.
The name attribute can be omitted here.

Example:

1. <form>
2. <label for="name">Enter name</label><br>
3. <input type="text" id="name" name="name"><br>
4. <label for="pass">Enter Password</label><br>
5. <input type="Password" id="pass" name="pass"><br>
6. <input type="submit" value="submit">
7. </form>

HTML <fieldset> element:

The <fieldset> element in HTML is used to group the related information of a form. This
element is used with <legend> element which provide caption for the grouped elements.

Example:

1. <form>
2. <fieldset>
3. <legend>User Information:</legend>
4. <label for="name">Enter name</label><br>
5. <input type="text" id="name" name="name"><br>
6. <label for="pass">Enter Password</label><br>
7. <input type="Password" id="pass" name="pass"><br>
8. <input type="submit" value="submit">
9. </fieldset>
10. lt;/form>

HTML Form Example

Following is the example for a simple form of registration.

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Form in HTML</title>
5. </head>
6. <body>
7. <h2>Registration form</h2>
8. <form>
9. <fieldset>
10. <legend>User personal information</legend>
11. <label>Enter your full name</label><br>
12. <input type="text" name="name"><br>
13. <label>Enter your email</label><br>
14. <input type="email" name="email"><br>
15. <label>Enter your password</label><br>
16. <input type="password" name="pass"><br>
17. <label>confirm your password</label><br>
18. <input type="password" name="pass"><br>
19. <br><label>Enter your gender</label><br>
20. <input type="radio" id="gender" name="gender" value="male"/>Male <br> 21.
<input type="radio" id="gender" name="gender" value="female"/>Fe male
<br/>
22. <input type="radio" id="gender" name="gender" value="others"/>others <br />
23. <br>Enter your Address:<br>
24. <textarea></textarea><br>
25. <input type="submit" value="sign-up">
26. </fieldset>
27. </form>
28. </body>
29. </html>

HTML Form Example

Let's see a simple example of creating HTML form.

1. <form action="#">
2. <table>
3. <tr>
4. <td class="tdLabel"><label for="register_name" class="label">Enter name:
</label></td>
5. <td><input type="text" name="name" value="" id="register_name" style=
"width:160px"/></td>
6. </tr>
7. <tr>
8. <td class="tdLabel"><label for="register_password" class="label">Enter p
assword:</label></td>
9. <td><input type="password" name="password" id="register_password" st
yle="width:160px"/></td>
10. </tr>
11. <tr>
12. <td class="tdLabel"><label for="register_email" class="label">Enter Email:
</label></td>
13. <td
14. ><input type="email" name="email" value="" id="register_email" style="widt
h:160px"/></td>
15. </tr>
16. <tr>
17. <td class="tdLabel"><label for="register_gender" class="label">Enter Gen
der:</label></td>
18. <td>
19. <input type="radio" name="gender" id="register_gendermale" value="male"
/>
20. <label for="register_gendermale">male</label>
21. <input type="radio" name="gender" id="register_genderfemale" value="fem
ale"/>
22. <label for="register_genderfemale">female</label>
23. </td>
24. </tr>
25. <tr>
26. <td class="tdLabel"><label for="register_country" class="label">Select Co
untry:</label></td>
27. <td><select name="country" id="register_country" style="width:160px"> 28.
<option value="india">india</option>
29. <option value="pakistan">pakistan</option>
30. <option value="africa">africa</option>
31. <option value="china">china</option>
32. <option value="other">other</option>
33. </select>
34. </td>
35. </tr>
36. <tr>
37. <td colspan="2"><div align="right"><input type="submit" id="register_0 "
value="register"/>
38. </div></td>
39. </tr>
40. </table>
41. </form>
HTML <kbd> tag

HTML <kbd> tag indicates the part of inline text which represents the user keyboard input,
voice input, or any other text entry device input.

The <kbd> text renders on the browser in default monospace font. It is used when a document
needs to display the text which user should enter exactly from his keyboard.

Syntax
1. <kbd>Enter Keyboard input</kbd>
Following are some specifications about the HTML <kbd> tag
Display Inline

Start tag/End tag Both Start and End tag

Usage Textual

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Kbd Tag</title>
5. <style>
6. kbd { border: 1px solid blue;
7. border-radius: 8px;
8. padding: 3px 5px;
9. margin: 2px;
10.
11. }
12. </style>
13. </head>
14. <body>
15. <h2>Example of Kbd tag</h2>
16. <p>If you are using MS document then you can use shortcut <kbd>ctrl + s<
/kbd> to save your current document. </p>
17. </body>
18. </html>
The MouseEvent Object

The MouseEvent Object handles events that occur when the mouse interacts with the HTML
document.

Mouse Events
Event Occurs When

onclick A user clicks on an element

oncontextmenu A user right-clicks on an element

ondblclick A user double-clicks on an element

onmousedown A mouse button is pressed over an element

onmouseenter The mouse pointer moves into an element

onmouseleave The mouse pointer moves out of an element

onmousemove The mouse pointer moves over an element

onmouseout The mouse pointer moves out of an element

onmouseover The mouse pointer moves onto an element

onmouseup A mouse button is released over an element


MouseEvent Properties
Property Returns

altKey If the ALT key is pressed

button Which mouse button is pressed

buttons Which mouse buttons were pressed

clientX The X coordinate of the mouse pointer (window relative) clientY The Y

coordinate of the mouse pointer (window relative) ctrlKey If the CTRL key is

pressed

detail The details about an event


metaKey If the META key is pressed

offsetX The X coordinate of the mouse pointer (target relative)

offsetY The Y coordinate of the mouse pointer (target relative)

pageX The X coordinate of the mouse pointer (document relative) pageY The Y

coordinate of the mouse pointer (document relative) relatedTarget The element that

triggered the mouse event

Screen The X coordinate of the mouse pointer (screen relative)

Screen The Y coordinate of the mouse pointer (screen relative)

shiftKey If the SHIFT key is pressed

Which Deprecated (Avoid using it)


Use the button property instead

2.3 Java Script

Our JavaScript Tutorial is designed for beginners and professionals both. JavaScript is used
to create client-side dynamic pages.
JavaScript is an object-based scripting language which is lightweight and cross-platform.
JavaScript is not a compiled language, but it is a translated language. The JavaScript
Translator (embedded in the browser) is responsible for translating the JavaScript code for the
web browser.

What is JavaScript

JavaScript (js) is a light-weight object-oriented programming language which is used


by several websites for scripting the webpages. It is an interpreted, full-fledged
programming language that enables dynamic interactivity on websites when applied
to an HTML document.

It was introduced in the year 1995 for adding programs to the webpages in the
Netscape Navigator browser. Since then, it has been adopted by all other graphical
web browsers.

With JavaScript, users can build modern web applications to interact directly without
reloading the page every time. The traditional website uses js to provide several
forms of interactivity and simplicity.

Although, JavaScript has no connectivity with Java programming language. The


name was suggested and provided in the times when Java was gaining popularity in
the market. In addition to web browsers, databases such as CouchDB and MongoDB
uses JavaScript as their scripting and query language.

Features of JavaScript

There are following features of JavaScript:

1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is
a structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather than
using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows, macOS,
etc.
8. It provides good control to the users over the web browsers.
History of JavaScript

In 1993, Mosaic, the first popular web browser, came into existence. In the year
1994, Netscape was founded by Marc Andreessen. He realized that the web
needed to become more dynamic. Thus, a 'glue language' was believed to be
provided to HTML to make web designing easy for designers and part-time
programmers.

Consequently, in 1995, the company recruited Brendan Eich intending to implement


and embed Scheme programming language to the browser. But, before Brendan
could start, the company merged with Sun Microsystems for adding Java into its
Navigator

so that it could compete with Microsoft over the web technologies and platforms.
Now, two languages were there: Java and the scripting language. Further, Netscape
decided to give a similar name to the scripting language as Java's. It led to
'Javascript'.

Finally, in May 1995, Marc Andreessen coined the first code of Javascript named
'Mocha'. Later, the marketing team replaced the name with 'LiveScript'. But, due to
trademark reasons and certain other reasons, in December 1995, the language was
finally renamed to 'JavaScript'. From then, JavaScript came into existence.

Application of JavaScript

JavaScript is used to create interactive websites. It is mainly used for:

o Client-side validation,

o Dynamic drop-down menus,

o Displaying date and time,

o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog
box and prompt dialog box),
o Displaying clocks etc.

<html>
<body>
<h2>Welcome to JavaScript</h2>
<script>
document.write("Hello JavaScript by JavaScript");
</script>
</body>
</html>
2.3.1 Overview of Client-Side& Server-Side Scripting

Difference between Server-side Scripting and Client-side Scripting

The scripts may be created in two ways: on the client side or the server side, where the server
side scripts are processed on a server. In contrast, client-side scripting needs browsers to
execute scripts on the client system but doesn't connect with the server executing the client
side scripts.

What is Server-side Scripting?

Server-side scripting is a programming technique for creating code that may run software on
the server side. In other words, server-side scripting is any scripting method that may operate
on a web server. At the server end, actions such as website customization, dynamic changes in
website content, response creation to user requests, database access, and many more are
carried out.

Server-side scripting creates a communication channel between a server and a client.


Previously, CGI (Common Gateway Interface) scripts were used to implement server-side
scripting, and CGI was created to execute scripts written in computer languages such as C++
or Perl on websites.

The server-side is made up of three parts: the database, the server, the APIs, and the backend
web software written in the server-side scripting language. When a browser requests a page
with server-side scripting, the web server evaluates the script before delivering the page to the
browser.

In this case, script processing may entail collecting information from a database, performing
simple computations, or selecting the relevant material to be shown on the client end. The
output is provided to the web browser when the script is processed. The web server hides the
scripts from the end user until the content is delivered, making the data and source code safer.

Server-side scripting languages

There are various server-side scripting languages. Some main server-side scripting languages
are as follows:

Python

It is an open-source language that is very powerful and easy to learn. It is suitable for
beginners because it is simple to learn and read. It is believed to be used by Google and
YouTube. It is a OOPs language with dynamic typing and data structures. It has grown to be
one of the most popular languages for both quick application development and web
development.

PHP
It is an open-source server-side scripting programming language mainly designed for web
apps and is the most utilized scripting language. It allows you to retrieve and manipulate data
from a database and is utilized along with SQL to query the database. It is a fast and simple
language to learn and develop, and Facebook, Wikipedia, and WordPress utilize it.
Ruby

It is a free and open-source programming language that was developed and firstly introduced
in the early 1990s. It is a dynamic language that is simple to read and write and an OOPs
language that is interpreted as it runs. It has evolved continuously since its development and is
one of the most utilized web development languages.

Features of Server-side Scripting

There are various features of server-side scripting. Some main features of the server-side
scripting are as follows:

1. It is connected with data access, error handling, and data processing speed.
2. It is processed and interacts with the server.
3. Using a highly integrated programming language makes it more secure than client-side
scripting.

What is Client-side Scripting?

Client-side scripting generates code that may be executed on the client end without needing
server-side processing. These scripts are typically embedded into HTML text. Client-side
scripting may be utilized to check the user's form for problems before submitting it and to
change the content based on the user input. The web needs three components to function:
client, database, and server.

The client-side scripting may significantly reduce server demand. It is intended to be utilized
as a scripting language with a web browser as the host program. The HTML and CSS are
delivered as plain text when a user uses a browser to request a webpage from the server, and
the browser understands and renders the web content at the client end.

Client-side Scripting Languages

There are various client-side scripting languages. Some main client-side scripting languages
are as follows:

HTML

It is not a scripting language; it is a markup language. However, it serves as the basic language
for client-side web development, also referred to as front-end. The presence of hypertext on a
page denotes its hyperlinks. The markup language uses tags to define the structure and layout.
It is a programming language that is mainly used to design a web page's structure and layout.
CSS

CSS is an abbreviation for Cascading Style Sheets. It provides a technique for creating
graphic elements that help a web application's appearance look more appealing. A style tag in
a web page defines all the specifics regarding the web page's presentation, including its
border styles, image styles, colour, font styles, borders, format, font size, margins, padding,
etc.
JavaScript

It is a client-side scripting language designed for a specific purpose, but several JavaScript
frameworks are already utilized as server-side scripting technologies.

VBScript

VBScript is based on Visual Basic, which was created by Microsoft in 1996. It is a scripting
programming language that is lightweight, fast, and easy to learn. It is not a OOPs language
but is similar to JavaScript.

Features of Client-side Scripting

There are various features of client-side scripting. Some main features of the client-side
scripting are as follows:

1. It is intended to execute code on which a web browser runs, and the results of the inputs
are delivered to an accessible user.
2. Client-side scripting enables greater involvement with clients via the browser and is
used to validate programs and functionality based on the request.
3. The client does not include any contact with the server in client-side scripting; the only
interaction is receiving the requested data.

Differences between the Server-side scripting and Client-side scripting 1. Server-side


scripting is utilized in the backend when the source code is invisible or hidden on the
client side. In contrast, client-side scripting is utilized at the front end, which users may
access via the browser.
2. The files are inaccessible to the client-side script. In contrast, the server-side script has
access to the files on the web server.
3. Server-side scripting is very useful for personalizing web pages and implementing
dynamic updates to websites. In contrast, the client-side script may effectively
minimize the load on the server.
4. The client-side script responds faster than the server-side script.
5. Client-side scripting is less secure than server-side scripting due to the server-side
scripts are commonly concealed from the client end. In contrast, the client-side scripts
are exposed to users.
6. The client-side script is run on a local computer. In contrast, the server-side script is
run on a remote machine.
7. The client-side programming languages are HTML, CSS, and JavaScript. In contrast,
server-side scripting programming languages, including PHP, ColdFusion, Python,
ASP.net, Java, C++, Ruby, C#,
8. A server-side script communicates with the server when it is executed. In contrast,
Client-side scripting doesn't need server involvement.
9. The script on the client side lacks security. However, the server-side script is protected.
10. The client-side script is dependent on the user's browser version. In contrast, the
Server side doesn't depend on the client.

comparison between Server-side Scripting and Client-side Scripting


The main differences between server-side scripting and client-side scripting are as follows:
Features Server-side Scripting Client-side Scripting

Primary Function The main function of this The main purpose of this scripting is
scripting is to manipulate and to give the requested output to the
grant access to the requested end user.
database.

Uses It is employed at the backend, It is utilized at the front end, which


where the source code is users may view through the browser.
invisible or concealed on the
client side.

Processing It needs server interaction. It doesn't need any server


interaction.

Security It is more secure while It is less secure than server-side


working on a web app. scripting due to the code
accessibility offered to the client.

Running It executes on the web server. It executes on the remote computer


system.

Dependability It doesn't depend on the client. It depends on the user's browser


version.
File Access It offers complete access to It doesn't offer any access to the
the file that is stored in the files on the web servers.
web database server.

Code Allowance It enables the backend The user is given access to the
developer to hide the source written code after confirming their
code from the user. requirements.

Occurrence It only responds after the user It happens when the browser
begins the browsing request. processes all of the codes and then
acts according to the client's needs.

Affect It may reduce the server load. It may effectively customize web
pages and offer dynamic websites.

Languages Involved The server-side scripting Its programming languages are HTML,
programming languages, such
as PHP, ColdFusion, Python,
ASP.net, Java, C++, Ruby,
C#, etc.

2.3.2 Structure of JavaScript


Introduction
JavaScript is a lightweight, interpreted programming language with object-oriented
capabilities that allows you to build interactivity into otherwise static HTML pages.
JavaScript code is not compiled but translated by the translator. This translator is embedded
into the browser and is responsible for translating JavaScript code.
Key Points
• It is Lightweight, interpreted programming language.
• It is designed for creating network-centric applications.
• It is complementary to and integrated with Java.
• It is complementary to and integrated with HTML
• It is an open and cross-platform

JavaScript Statements
JavaScript statements are the commands to tell the browser to what action to perform.
Statements are separated by semicolon (;).
JavaScript statement constitutes the JavaScript code which is translated by the browser line
by line.
Example of JavaScript statement:
document.getElementById("demo").innerHTML = "Welcome";

Following table shows the various JavaScript Statements −


Sr.No. Statement Description

1. switch case A block of statements in which execution of code depends upon different
cases. 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.

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

3. While The purpose of a while loop is to execute a statement or code block repeatedly
as long as expression is true. Once expression becomes false, the loop will be
exited.

4. do while Block of statements that are executed at least once and continues to be
executed while condition is true.

5. for Same as while but initialization, condition and increment/decrement is done


in the same line.

6. for in This loop is used to loop through an object's properties.

7. continue The continue statement tells the interpreter to immediately start the next
iteration of the loop and skip remaining code block.

8. break The break statement is used to exit a loop early, breaking out of the
enclosing curly braces.

9. Function A function is a group of reusable code which can be called anywhere in


your programme. The keyword function is used to declare a function.

10. Return Return statement is used to return a value from a function.

11. Var Used to declare a variable.

12. Try A block of statements on which error handling is implemented.

13. Catch A block of statements that are executed when an error occur.

14. Throw Used to throw an error.

JavaScript Comments
JavaScript supports both C-style and C++-style comments, thus:
• Any text between a // and the end of a line is treated as a comment and is ignored
by JavaScript.
• Any text between the characters /* and */ is treated as a comment. This may span
multiple lines.
• JavaScript also recognizes the HTML comment opening sequence <!--.
JavaScript treats this as a single-line comment, just as it does the // comment.--
>
• The HTML comment closing sequence --> is not recognized by JavaScript so it
should be written as //-->.
Example
<script language="javascript" type="text/javascript">
<!--

// this is a comment. It is similar to comments in C++

/*
* This is a multiline comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
<script>

2.3.3 Data Types and Variables


JavaScript variable
Variables are referred as named containers for storing information. We can place data into
these containers and then refer to the data simply by naming the container.
Rules to declare variable in JavaScript
Here are the important rules that must be followed while declaring a variable in JavaScript.
• In JavaScript variable names are case sensitive i.e. a is different from A. • Variable
name can only be started with a underscore ( _ ) or a letter (from a to z or A to Z),
or dollar ( $ ) sign.
• Numbers (0 to 9) can only be used after a letter.
• No other special character is allowed in variable name.

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, age;
//-->
</script>
Variables can be initialized at time of declaration or after declaration as follows −
<script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>

Javascript Data Type


There are two kinds of data types as mentioned below −
• Primitive Data Type
• Non-Primitive Data Type

The following table describes Primitive Data Types available in javaScript


Sr.No. Datatype Description

1. String
Can contain groups of character as single value. It is represented in double quotes.E.g.
var x= “tutorial”.

2. Numbers
Contains the numbers with or without decimal. E.g. var x=44, y=44.56;

3. Booleans
Contain only two values either true or false. E.g. var x=true, y= false.

4. Undefined
Variable with no value is called Undefined. E.g. var x;

5. Null
If we assign null to a variable, it becomes empty. E.g. var x=null;

The following table describes Non-Primitive Data Types in javaScript


Sr.No. Datatype Description
1. Array
Can contain groups of values of same type. E.g. var x={1,2,3,55};

2. Objects
Objects are stored in property and value pair. E.g. var rectangle = { length: 5,
breadth: 3};

2.3.4 Operators (Arithmetic Operator, Assignment Operator, Comparison


Operator, Logical Operator, Conditional Operator)

JavaScript Operators
Operators are used to perform operation on one, two or more operands. Operator is
represented by a symbol such as +, =, *, % etc. Following are the operators supported by
JavaScript −
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
• Arithmetic Operators

Arithmetic Operators
Following table shows all the arithmetic operators supported by JavaScript −
Operator Description Example

+ Add two operands. 10 + 10 will give 20

- Subtract second operand from the first. 10 – 10 will give 0

* Multiply two operands. 10 * 30 will give


300

/ Divide numerator by denominator 10/10 will give 1

% It is called modulus operator and gives remainder of 10 % 10 will give 0


the division.
++ Increment operator, increases integer value by one 10 ++ will give 11

-- Decrement operator, decreases integer value by one 10 – will give 9

Comparison Operators
Following table shows all the comparison operators supported by JavaScript −
Operator Description Example

== Checks if values of two operands are equal or not, If yes 10 == 10 will


then condition becomes true. give true

!= Not Equal to operator 10 !=10 will


Checks if the value of two operands is equal or not, if values give false
are not equal then condition becomes true.

> Greater Than operator 20 > 10 will


Checks if the value of left operand is greater than the value give true
of right operand, if yes then condition becomes true.

< Less than operator 10 < 20 will


Checks if the value of left operand is less than the value of give true
right operand, if yes then condition becomes true.

>= Greater than or equal to operator 10 >=20 will


Checks if the value of left operand is greater than or equal to give false
the value of right operand, if yes then condition becomes
true.

<= Less than or equal to operator 10 <=20 will


Checks if the value of left operand is less than or equal to give true.
the value of right operand, if yes then condition becomes
true.

Logical Operators
Following table shows all the logical operators supported by JavaScript −
Operator Description Example
&& Logical AND operator returns true if both operands 10 && 10 will give
are non-zero. true.

|| Logical OR operator returns true If any of the operand 10 || 0 will give true.
is non zero

! Logical NOT operator complements the logical state ! (10 && 10) will
of its operand. give false.

Assignment Operators
Following table shows all the assignment operators supported by JavaScript −
Operator Description Example

= Simple Assignment operator C = A + B will


Assigns values from right side operands to left assign value of A
side operand. + B into C

+= Add AND assignment operator C += A is equivalent to


It adds right operand to the left operand and assign C =C+A
the result to left operand

-= Subtract AND assignment operator C -= A is equivalent to


It subtracts right operand from the left operand C =C-A
and assign the result to left operand

*= Multiply AND assignment operator C *= A is equivalent to


It multiplies right operand with the left operand C =C*A
and assign the result to left operand

/= Divide AND assignment operator C /= A is equivalent to


It divides left operand with the right operand and C =C/A
assign the result to left operand

%= Modulus AND assignment operator C %= A is equivalent


Modulus AND assignment operator, It takes to C = C % A
modulus using two operands and assign the result to
left operand
Conditional Operator
It is also called ternary operator, since it has three operands.
Operator Description Example

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

2.3.5 Control Structure (If…Else, While, Do…While, For)

Control Structure
Control structure actually controls the flow of execution of a program. Following are the
several control structures supported by JavaScript.
• if … else
• switch case
• do while loop
• while loop
• for loop
If … else
The if statement is the fundamental control statement that allows JavaScript to make decisions
and execute statements conditionally.
Syntax
if (expression){
Statement(s) to be executed if expression is true
}

Example
<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>

Switch case
The basic syntax of the 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.
Syntax
switch (expression) {
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}

Example
<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>

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
do{
Statement(s) to be executed;
} while (expression);

Example
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br/>");
do{
document.write("Current Count : " + count + "<br/>");
count++;
}while (count < 0);
document.write("Loop stopped!");
//-->
</script>

This will produce following result −


Starting Loop
Current Count : 0
Loop stopped!
While Loop
The purpose of a while loop is to execute a statement or code block repeatedly as long as
expression is true. Once expression becomes false, the loop will be exited.
Syntax
while (expression){
Statement(s) to be executed if expression is true
}

Example
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br/>");
while (count < 10){
document.write("Current Count : " + count + "<br/>");
count++;
}
document.write("Loop stopped!");
//-->
</script>
This will produce following result −
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
For Loop
The for loop is the most compact form of looping and 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 the given condition is true or not. If
condition is true then code given inside the loop will be executed otherwise
loop will come out.
• The iteration statement where you can increase or decrease your counter.
Syntax

for (initialization; test condition; iteration statement){


Statement(s) to be executed if test condition is true
}
Example
<script type="text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br/>");
for(count = 0; count < 10; count++){
document.write("Current Count : " + count );
document.write("<br/>");
}
document.write("Loop stopped!");
//-->
</script>

This will produce following result which is similar to while loop −


Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Creating Sample Program
Following is the sample program that shows time, when we click in button.
<html>
<body>
<button onclick="this.innerHTML=Date()">The time is?</button>
<p>Click to display the date.</p>
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}</script>

<p id="demo"></p>
</script>
</body>
</html>

2.3.6 Functions
JavaScript Functions
Function is a group of reusable statements (Code) that can be called anywhere in a program.
In JavaScript function keyword is used to declare or define a function.
Key Points
• To define a function use function keyword followed by function name, followed
by parentheses ().
• In parenthesis, we define parameters or attributes.
• The group of reusable statements (code) is enclosed in curly braces {}. This code
is executed whenever function is called.
Syntax
function functionname (p1, p2) {
function coding…
}

You might also like